Reputation: 10828
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.
Upvotes: 1
Views: 45
Reputation: 1353
Try:
$shops = Shop::with('devices')
->where('user_id', $userId)
->where('guid', '!=', null)->get();
$get_count = count($shops); // it return how many values have $shops
OR
$shops= DB::table('devices')->where('user_id', $userId)
->where('guid', '!=', null)->get();
$get_count = count($shops);
if you did not have the class DB add at your controller:
use DB;
Upvotes: 0
Reputation: 163748
Since $item->devices
is a collection there is no whereNotNull()
for collections. So try to use where()
:
$item->devices->where('guid', '<>', null)->count();
Upvotes: 1