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?
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.
Use method setEncodingOptions
of JsonResponse
:
return response()->json($properties)->setEncodingOptions(JSON_NUMERIC_CHECK);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With