1

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.

2 Answers 2

1

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

$item->devices->where('guid', '<>', null)->count(); 
Sign up to request clarification or add additional context in comments.

Comments

0

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; 

1 Comment

That will return number of shops, not devices.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.