DerJacques
DerJacques

Reputation: 332

Query a relationship in Laravel with WHERE method

I have a model called "User", which "belongsToMany" Items. This relationship works fine, so I can easily do something like this:

User::find(4)->items->find(1)->name

Now, I would like to do something like this:

User::find(4)->items->where('name', '=', 'stick')->get()

I would expect the code to return all the user's items with the name "stick", but unfortunately that is not what happens. I receive this error:

"Call to undefined method Illuminate\Database\Eloquent\Collection::where()"

I also tried to build a query scope:

public function scopeName($query, $name)
{
    return $query->whereName($name);
}

The query scope works when I do something like this:

Item::name('SC')->get()

but

User::find(4)->items->name('SC')->get() 

still does not work.

Can you help me returning all the user's items, which have the name 'stick'?

Upvotes: 0

Views: 2736

Answers (2)

David Hemphill
David Hemphill

Reputation: 1102

If you're looking to just get a single user's items named "stick", this is how you would do it:

$stickItems = Item::whereUserId(4)->whereName('stick')->get();

Here we are using Eloquent's dynamic where methods, but you could rewrite it like so:

$stickItems = Item::where('user_id', '=', 4)->where('name', '=', 'stick')->get();

That should get you what you want.

Upvotes: 1

Joseph Silber
Joseph Silber

Reputation: 219920

You have to call the items() method, not use the magic property:

User::find(4)->items()->where('name', 'stick')->get();
//                  ^^

Upvotes: 0

Related Questions