user8504877
user8504877

Reputation:

How to filter a Laravel collection

I have to following eloquent db statements in my function. Two read statements on the db.

$groups = V_Member::where('groupadmin', '=', Auth::id())->get();    
$members = V_Member::where([['idgroup', $groupid],['groupadmin', Auth::id()]])->get();

First I want to execude the first db statement and then I want to filter on the collection/variable. Like this below. But I get an error. What I have to change?

$groups = V_Member::where('groupadmin', '=', Auth::id())->get();
$members = $groups::where(['idgroup', '=', $groupid])->get();

This is the error message

Non-static method Illuminate\Support\Collection::where() should not be called statically

Upvotes: 1

Views: 309

Answers (3)

Marcin Nabiałek
Marcin Nabiałek

Reputation: 111899

You can just use:

$members = $groups->where('idgroup', $groupid);

Operator= is not necessary but you can use it where you want. You can also take a look at where method documentation.

Upvotes: 1

Erubiel
Erubiel

Reputation: 2972

Since $groups is a collection and not a Model Class...

You should use ->where() instead of ::where()

Don't confuse collections with eloquent querys, it's a common mistake.

Also, don't confuse methods for building querys with eloquent, with methods for collections, another common mistake.

Upvotes: 1

Rwd
Rwd

Reputation: 35220

If you want to filter the collection instead of running 2 queries, then you will just need to change:

$members = $groups::where(['idgroup', '=', $groupid])->get();

to:

$members = $groups->where('idgroup', '=', $groupid);

For more information you can have a look at the documentation

Upvotes: 1

Related Questions