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?
Advertisement
Answer
when you call Shift::all() you get all the shifts table record from db as a collection , then you load the relation on that collection which makes that error.
you should not be loading the result from db unless your query is ready, you should tell the query builder to load the relation then call the result:
$shifts = Shift::withStatus() ->withProfession() ... ->get();