Laravel 5 controller sending JSON integer as string

Solution 1:

I just ran into this same issue! For those of you looking for a more appropriate solution, you might want to check out the $casts property for Eloquent models.

The accepted solution will work, but it will also convert fields that you may not want converted. I would recommend adding this to your Eloquent model:

protected $casts = [ 'imdb_rating' => 'float', 'imdb_votes' => 'integer' ];

This will convert the values directly in your model object, so you won't need to worry about updating multiple endpoints. I hope this helps others as it did me!

Solution 2:

Make sure to use MySQL Native Driver which will support native data types.

It is possible to convert integer and float columns back to PHP numbers by setting the MYSQLI_OPT_INT_AND_FLOAT_NATIVE connection option, if using the mysqlnd library. If set, the mysqlnd library will check the result set meta data column types and convert numeric SQL columns to PHP numbers, if the PHP data type value range allows for it. This way, for example, SQL INT columns are returned as integers.

MySQL Client Library will return all fields as strings.

Another solution would be to use json_encode options with JSON_NUMERIC_CHECK.

For example:

return response()->json(["foo" => "bar"], 200, [], JSON_NUMERIC_CHECK);