Answer the question
In order to leave comments, you need to log in
Why does Query Builder in Laravel 5.2 return an object?
I want to count the number of records by condition with the following code:
public function scopeActive_cnt($query)
{
return $query->where('active',1)->count();
}
Model::active()->count();
select count(*) as aggregate from `table`
Answer the question
In order to leave comments, you need to log in
Because scopes are not designed to call the fetch method (get, paginate, count, etc.) in them. There you can only impose restrictions. The Laravel logic expects a Builder to be returned from scope.
Model::active()->count(); can be placed in a separate method so as not to write each time if it is too long for you.
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question