Laravel Response::json() with numeric check
json, laravel, laravel-4, php
Solution
You can actually pass that option over. If we take a look at the source code for the JsonResponse class you can pass json_encode options as the last parameter.
It would look something like this
return Response::json($properties, 200, [], JSON_NUMERIC_CHECK);
Alternatively you could do this:
return Response::make(
$properties->toJson(JSON_NUMERIC_CHECK),
200,
['Content-Type' => 'application/json']
);
Note: if `$properties` is not an Elequoent model then it must at least implement the JsonableInterface
as well as:
return Response::make(
json_encode($properties->toArray(), JSON_NUMERIC_CHECK),
200,
['Content-Type' => 'application/json']
);
The toJson() method in Eloquent just wraps `json_encode()` and passes it the array of your model. I'd recommend using one of the first two options.
Problem
When performing an eloquent query on a model (using the MySQL driver) which has some numeric fields and then return a json response of the results, the json appears to pass numeric values as strings rather than numbers. E.g. ``` $properties = Model::find(6); return Response::json($properties); ``` Returns something like: ``` { "name": "A nice item", "value": "160806.32" } ``` When it should return: ``` { "name": "A nice item", "value": 160806.32 } ``` In normal php you can use the `JSON_NUMERIC_CHECK` to solve this but there appears to be no such option for the `Response::json()` method. How can I ensure numeric fields are returned as numbers rather than strings?