I Want To Use Relation Methods In Scopes But It Gives an Error.
Error:
Call to undefined method IlluminateDatabaseEloquentBuilder::members()
Controller:
$members = $book->MembersLoanedCurrentBook()->paginate(8);
Scope:
public function scopeMembersLoanedCurrentBook(Builder $query): Builder
{
return $query->members()->orderBy('return_date')->where('book_member.returned',false);
}
2
Answers
Assuming your models are something akin to
User hasMany BookMember
andBook has an attribute called
returned, you can use Laravel's
with` query scope:@geertjanknapen was right that this is a possible duplicate. You can achieve the same result using the methods from this question.
What you are doing is defining a scope and in that scope querying a relationship for a specific property or value.
}
Without knowing the model structure and relationships, it’s hard to write out an exact solution, but something along these lines should work.
You can’t work with relations in scope, because your work with Builder $query.
And