mr.incredible
mr.incredible

Reputation: 4165

Laravel 5.6 how to preserve float and int values in json response?

Searching about 20 minutes and still can't find reliable answer how to simply configure json respone for float type.

$array = DB::select('SELECT name, balance FROM ... blah blah blah'); // balance is float

return response()->json([
   'data' => $array
]);

It returns:

{"data":[
   {"name":"bob","balance":"889.37700000000018"},
   {"name":"john","balance":"705.77400000000011"}
]}

So, as you might guess I want to have float type in this json data for balance values:

{"data":[
   {"name":"bob","balance":889.37700000000018},
   {"name":"john","balance":705.77400000000011}
]}

I can use standard json_encode() function with JSON_PRESERVE_ZERO_FRACTION flag to solve this issue.

But how to do the same thing with response()->json() ?

I've tried this sample but it fails and error occurs:

return response()->json([
      'data' => $array
   ],
   Response::HTTP_OK,
   [],
   JSON_PRESERVE_ZERO_FRACTION
);

Upvotes: 2

Views: 4980

Answers (2)

mr.incredible
mr.incredible

Reputation: 4165

I solved it by sorting query result and casting balance value to float in foreach loop.

$array= [];

foreach($result as $row) {
   array_push($array, [
      'name' => $row->name,
      'balance' => (float) $row->balance
   ]);
}

return response()->json([
   'data' => $array
]);

Upvotes: 1

Farooq Ahmed Khan
Farooq Ahmed Khan

Reputation: 4094

You can casts your model attributes by providing a mapping as

class UserModel {

    // mention mapping to primitive data-types as [int, float, boolean, decimal, real, array, object]
    protected $casts = array(
        "is_admin" => "boolean",
        "age" => "integer",
        "salary" => "float",
        "certificates" => "array"
    );
}

Resulted serialized model JSON will be casted as per your mappings.

[
    {
        "is_admin": true,
        "age": 30,
        "salary":  100.12,
        "cetificates": []
    }
]

Upvotes: 4

Related Questions