skip to Main Content

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


  1. Assuming your models are something akin to User hasMany BookMember and Book has an attribute called returned, you can use Laravel's with` query scope:

    Users::with(['member_books', function ($q) => {
        $q->returned
    })->get();
    

    @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.

    public function scopeMembersLoanedCurrentBook(Builder $query): Builder
    {
        return $query->members()
                     ->orderBy('return_date')
                     ->whereHas(['book', function ($q) => {
                          $q->returned == false;
                     });
    });
    

    }

    Without knowing the model structure and relationships, it’s hard to write out an exact solution, but something along these lines should work.

    Login or Signup to reply.
  2. You can’t work with relations in scope, because your work with Builder $query.

    public function scopeMembersLoanedCurrentBook(Builder $query): Builder
        {
            return $query->orderBy('return_date')
            ->where('returned',false);
        }
    

    And

    $members = $book->members()->MembersLoanedCurrentBook()->paginate(8);
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search