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?
Try casts property for all boolien fields in model.
protected $casts = [
'is_published' => 'boolean',
];
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With