Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Laravel Response::json() with numeric check

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?

like image 399
harryg Avatar asked Jun 02 '14 14:06

harryg


2 Answers

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.

like image 162
Kirill Fuchs Avatar answered Nov 20 '22 02:11

Kirill Fuchs


Use method setEncodingOptions of JsonResponse:

return response()->json($properties)->setEncodingOptions(JSON_NUMERIC_CHECK);
like image 38
Malta Avatar answered Nov 20 '22 01:11

Malta