monsterdream's avatar

count() in model scope return Builder collection

Hi, I have a problem with count() in model scope. When it has any count above 0 to return then is ok, but when count() is equal to 0 it returns Builder collection instead of "0". When I call count() method in controller then it works, but I would like to clear that part and keep it in model scope. Is here any "hack" for that ?

    public function scopeGetCountForAllCategoriesForLocation($query)
    {
        return $query->where('active', 1)->count() ;
    }
0 likes
4 replies
bestmomo's avatar

I guess query returns null if you dont get rows so try something like that :

public function scopeGetCountForAllCategoriesForLocation($query)
{
    $q = $query->whereActive(1)->count() ;
    return $q === null ? 0 : $q;
}
monsterdream's avatar

Yes, of course I could do that but I not sure if this is "elegant" way... I found solution. It works, but maybe someone will have another approach for that:

public static function getCountForAllCategoriesForLocation()
{
    return static::where('active', 1)->count() ;
}
jlrdw's avatar

You said.

I not sure if this is "elegant" way.

You realize the docs also covers database and query builder. All solutions doesn't have to be done using eloquent.

monsterdream's avatar

@jlrdw Yes, I know that and I really appreciate @bestmomo answer. That was only my opinion, no offense. It's good to know many possibilities if any exist.

Please or to participate in this conversation.