Reputation: 1993
I have the following scope:
public function scopeLabel($query, $label)
{
return $query->with(['label' => function ($q) use ($label) {
$q->where('name', '=', $label)->get();
}]);
}
Which I then use as follows:
$appointments = Appointment::latest('created_at')->label($label)->get();
The $label is fetched from a POST form and it matches the name field of my labels table.
The above query works when I call it directly from the controller, like so:
Appointment::with(['label' => function ($q) use ($label) {
$q->where('name', '=', $label)->get();
}])->get();
This then returns all results from my Appointments
table, where the appointments.label_id
matches the labels.id
in the Labels
table. I hope you're still with me :)
But when I use the query in a scope, like the above, it doesn't work. It simply returns all results, and I cannot seem to figure out why this is. Any pointers?
Upvotes: 3
Views: 1413
Reputation: 1993
Answered already once, similar issue I had, and I didn't learn anything from it, shame on me.
$appointment = App\Appointment::whereHas('label', function ($query) use ($label){
$query->where('name', '=', $label);
})
->with(['status' => function($query) use ($label){
$query->where('name', '=', $label);
}])->get();
Upvotes: 1