Using a query scope in a collection laravel

9.8k views Asked by At

My Association model looks like this (irrelevant code redacted):

class Association extends Model
{
    public function members() {
        return $this->hasMany('App\Member');
    }

}

My Member model looks like this:

class Member extends Model
{
    public function scopeActive($query) {
        return $query->where('membership_ended_at', Null);
    }
    public function scopeInactive($query) {
        return $query->whereNotNull('membership_ended_at');
    }
}

This is what I want to be able to do:

$association = Association::find(49);
$association->members->active()->count();

Now, I'm aware there's a difference between a Query and a Collection. But what I'm basically asking is if there's some kind of similar scope for collections. Of course, the optimal solution would be to not have to write TWO active methods, but use one for both purposes.

1

There are 1 answers

0
Artenes Nogueira On BEST ANSWER

(question already answered in the comments, but might as well write a proper answer)

It is not possible to use a query scope in a Colletion, since query scope is a concept used in Eloquent to add constraints to a database query while Collections are just a collection of things (data, objects, etc).

In your case, what you need to do is to change this line:

$association->members->active()->count();

to:

$association->members()->active()->count();

This works because when we call members as a method, we are getting a QueryBuilder instance, and with that we can start chaining scopes to the query before calling the count method.