Using request scope in laravel collection

My association model looks like this (irrelevant code changed):

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

My member model is as follows:

 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 do:

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

Now I know that there is a difference between Query and Collection. But I basically ask if there is some kind of similar area for collections. Of course, the optimal solution would be not to write two active methods, but to use them for both purposes.

+6
source share
1 answer

(the question has already been answered in the comments, but the minus also wrote the correct answer)

You cannot use a query scope in Colletion , because a query scope is a concept used by Eloquent to add restrictions to a database query, whereas Collections is just a collection of things (data, objects, etc.).).

In your case, you need to change this line:

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

in

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

This works because when we call members as a method, we get an instance of QueryBuilder , and with that we can start attaching regions to the query before calling the count method.

+3
source

Source: https://habr.com/ru/post/989405/


All Articles