Laravel Response :: json () with a numerical check

When making an eloquent query on a model (using the MySQL driver) that has multiple numeric fields and then returns a json response of the results, json seems to pass the numeric values ​​as strings, not numbers.

eg.

$properties = Model::find(6); return Response::json($properties); 

It returns something like:

 { "name": "A nice item", "value": "160806.32" } 

What time is he expected back:

 { "name": "A nice item", "value": 160806.32 } 

In regular php, you can use JSON_NUMERIC_CHECK to solve this problem, but there seems to be no such method for the Response::json() method. How can I guarantee that numeric fields are returned as numbers, not strings?

+6
source share
2 answers

You can pass this option. If we look at the source code for the JsonResponse class , you can pass json_encode parameters as the last parameter.

It will look something like this.

 return Response::json($properties, 200, [], JSON_NUMERIC_CHECK); 

Alternatively you can do this:

  return Response::make( $properties->toJson(JSON_NUMERIC_CHECK), 200, ['Content-Type' => 'application/json'] ); 

Note: if $properties not an Elequoent model, then it should at least implement JsonableInterface

as well as :

  return Response::make( json_encode($properties->toArray(), JSON_NUMERIC_CHECK), 200, ['Content-Type' => 'application/json'] ); 

Method

+20
source

Use the setEncodingOptions of JsonResponse :

 return response()->json($properties)->setEncodingOptions(JSON_NUMERIC_CHECK); 
+4
source

Source: https://habr.com/ru/post/970185/


All Articles