Search code examples
phplaraveleloquentlaravel-collection

Count from other table


I am having problem to count number of devices where guid is not null.

It need to get all the shops by user user_id and then count all the devices where guid is not null.

$shops = Shop::with('devices')->where('user_id', $userId)->get();

$deviceActive = $shops->reduce(function ($carry, $item) {
     return $carry + $item->devices->whereNotNull('guid')->count();
});

dd($deviceActive );

It work when I do:

return $carry + $item->devices->count();

but it need to count where guid is not null.

I would also be interested to hear if there is alternative reduce approach.


Solution

  • Since $item->devices is a collection there is no whereNotNull() for collections. So try to use where():

    $item->devices->where('guid', '<>', null)->count();