M
M
Maxim Vlasov2017-04-02 14:42:44
Laravel
Maxim Vlasov, 2017-04-02 14:42:44

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();
}

If there is at least one entry, then a number is returned, but if there are no entries, then the builder object is returned. How to count as a builder?
I don’t want to do this:
Model::active()->count();
So it seems that it counts how many returned, but I need a query like:
select count(*) as aggregate from `table`

Answer the question

In order to leave comments, you need to log in

1 answer(s)
V
Victor, 2017-04-02
@tr0yka

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 question

Ask a Question

731 491 924 answers to any question