I have a model called Shift on my application, and I've defined my relationships and scopes on it like this:
Relationship:
public function status()
{
return $this->belongsTo(ShiftStatus::class);
}
With scope:
public function scopeWithStatus($query)
{
$query->with('status');
}
Now, when I retrieve shifts and try to call these scopes, I do the following:
$shifts = Shift::all()
->withStatus()
->withProfession()
...
->get();
return response([
'message' => 'Shifts retrieved.',
'shifts' => $shifts
]);
However, I get this error...
"message": "Method Illuminate\\Database\\Eloquent\\Collection::withStatus does not exist.",
I'm not sure why this is happening? It should pick up the scope shouldn't it?
My Answer:
The issue here is that you are trying to call the `withStatus()` scope on the collection returned by `Shift::all()`, but scopes are meant to be called on the query builder instance, not on the collection.
To fix this issue, you should modify your code like this:
php
$shifts = Shift::withStatus()
->withProfession()
...
->get();
return response([
'message' => 'Shifts retrieved.',
'shifts' => $shifts
]);
By calling the `withStatus()` scope directly on the `Shift` model query builder instance, you should be able to retrieve the shifts with the status relationship loaded correctly.
Rate this post
5 of 5 based on 7127 votesComments