You can use attribute casting on model for this.
http://laravel.com/docs/5.1/eloquent-mutators#attribute-casting
Can Eloquent preserve data types? Everything is being returned as string
I'm doing this in my controller:
$property = Property::findOrFail($id);
return response()->json(['property' => $property]);
The JSON response that comes out does the preserve the original datatypes I set in the Database. Here is a sample response for that request:
{
"id": "4",
"name": "Flatiron Building",
"address1": "175 5th Ave",
"address2": "",
"city": "New York",
"state": "NY",
"zip": "10010",
"total_sq_ft": "250000",
"occupied_sq_ft": "225000",
"vacant_sq_ft": "25000",
"created_at": "2015-11-30 23:31:16",
"updated_at": "2015-11-30 23:31:16",
}
The id, total_sq_ft, occupied_sq_ft and vacant_sq_ft should be integers, but are coming out as strings.
After doing a var_dump() on $property I noticed that all the keys and the values under attributes property (is this the correct property I should be looking at?) are strings. This is why I'm thinking Eloquent models are distorting the original data types and converting everything to a string.
How do I keep the data types intact?
This doesn't happen on my end. Check out this answer on SO: http://stackoverflow.com/questions/20079320/php-pdo-mysql-how-do-i-return-integer-and-numeric-columns-from-mysql-as-int
It looks like it depends on your mysql driver.
Please or to participate in this conversation.