Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 746
RRR Avatar asked Feb 10 '19 06:02

RRR


1 Answers

Try casts property for all boolien fields in model.

protected $casts = [
    'is_published' => 'boolean',
];
like image 54
Mipel Avatar answered Oct 06 '22 22:10

Mipel