Reputation: 992
I have a query that returns a boolean field (by the way, I'm on an SQL Server) on my REST API developed with Laravel and a few days ago it was returning the value as true/false, but now it returns that boolean value as String: "1"/"0".
Any idea on what could it be?
I tried using casting on my Model like this:
protected $casts = [
'status' => 'boolean',
];
This is my query:
return DB::table('dbo.visits as V')
->leftJoin('dbo.reports AS R', 'R.id_visit', '=', 'V.id')
->select('R.id','R.status'); // status is the boolean
Upvotes: 13
Views: 29292
Reputation: 906
You could use Eloquent: API Resources
/*Controller*/
$sel_visit= Visit::leftJoin('dbo.reports AS R', 'R.id_visit', '=', 'dbo.visits.id')->select('R.id','R.status')->get(); // status is the boolean
VisitResource::collection($sel_visit);
Then using a API Resources
public function toArray($request)
{
if($this->status==1) { $status=true;} else {$status=false;}
return [
'id' => $this->id,
'status' => $status
];
}
Upvotes: 0
Reputation: 335
What you would like to do is add this function to your model. Every time you use your model to retrieve data, this function matching the attribute name will be called to convert your raw data from the database to your desired format.
public function getStatusAttribute($value)
{
return $value ? 'Yes' : 'No';
}
Upvotes: 0
Reputation: 111829
Defining casts is working when you are using Eloquent models. In code you provided you use query builder and then Eloquent models are not used at all, so no casts are done.
Upvotes: 2
Reputation: 29268
When you're defining the following:
protected $casts = [
'status' => 'boolean',
];
You're defining it on the model. However, when you initiate your query using DB::table()
, you're not using the model, so the binding doesn't actually apply. Initiate your query using your model:
return Visit::leftJoin('dbo.reports AS R', 'R.id_visit', '=', 'dbo.visits.id')
->select('R.id','R.status'); // status is the boolean
Note: Had to adjust query to dbo.visits.id
from V.id
due to aliasing not being available at that point.
Upvotes: 26