Laravel: Unexpected date behavior in JSON Response

I am making a web service in Laravel that returns JSON.

I created the Account model as follows:

 class Account extends Eloquent { // The database table used by the model. // (If not defined then lowercase and plural of class name is consider as a table name) protected $table = "account"; // define which column can be mass assign protected $fillable = array("user_id", "account_group_id", "generated_by", "image", "name", "address", "zip", "area_id", "mobile", "email", "phone", "fax", "website", "pan", "cst", "tin", "ecc", "iesc", "transport", "other", "outstanding", "cform", "status", "mitp"); // To prevent column from mass assignment. protected $guarded = array('id'); // Change Variable for CREATED_AT and UPDATED_AT const CREATED_AT = 'itp'; const UPDATED_AT = 'utp'; } 

I retrieve fields from Account using user_id and return JSON via Response::json() in my controller

 $accountData = Account::select('name', 'status', 'id', 'user_id', 'utp')->where('user_id', Auth::id())->first(); $return = array( 'result' => 'success', 'msg' => 'Login Successfully.', 'data' => $accountData ); return Response::json($return); 

In this, utp behaves as expected and returns the date as a string:

 { "result": "success", "msg": "Login Successfully.", "data": { "name": "Demo", "status": 0, "id": 143, "user_id": 207, "utp": "2015-07-01 18:38:01" } } 

However, if I take each value separately from the account model, for example:

 $return = array( 'result' => 'success', 'msg' => 'Login Successfully.', 'data' => $accountData['user_id'], 'account_id' => $accountData['id'], 'utp' => $accountData['utp'], 'usertype' => 'account', 'status' => $accountData['status'] ); 

Then it gives some unexpected behavior from utp

 { "result": "success", "msg": "Login Successfully.", "data": 207, "account_id": 143, "utp": { "date": "2015-07-01 18:38:01", "timezone_type": 3, "timezone": "Asia\\/Kolkata" }, "usertype": "account", "status": 0 } 

Why is this happening with my timestamp field?

+5
source share
1 answer

Because utp is an instance of Carbon\Carbon . Model::toJson (actually Model::toArray , but both are used) handles that normally and serializes the date for it in the usual ISO3601-ish format

For the expected behavior, you need to format the Carbon instance.

 "utp" => $accountData['utp']->format("Ymd H:i:s"), 

Alternatively, add it to the line

 "utp" => (string) $accountData['utp'], 
+5
source

All Articles