Skip to content
Advertisement

PHP Laravel – Eloquent is returning boolean fields randomly sometimes as 0 1 and others as true false when calling the method json

I am using Laravel Eloquent to write a REST API. When calling json from response() to return the object, boolean fields are returned as 0/1 sometimes and as false/true others. I would like to unify the format and make it all as 0,1 or as false,true instead of it being random

here is the code sample:

public function show($id)
{
    $obj = MyObject::findOrFail($id);
    return response()->json($obj,200);
}

this return 0,1

and this code when the object is created return true, false not only for the status but for the boolean values in the $obj

return response()->json([
        'status' => (bool) $obj,
        'data'   => $obj,
        'message' => $obj ? 'new obj created!' : 'an error has occurred'
    ], 201); 

So, how to make them all 0 and 1 or all true or false?

Advertisement

Answer

Try casts property for all boolien fields in model.

protected $casts = [
    'is_published' => 'boolean',
];
User contributions licensed under: CC BY-SA
3 People found this is helpful
Advertisement