Miguel Stevens
Miguel Stevens

Reputation: 9191

Laravel nested where using eloquent

I'm using eloquent to build a query but i'm stuck in the final phase.

$city = City::where('name', $event)->first()->event;

This is working and returns all 3 events for this city, as shown in the screenshot

enter image description here

I want to perform another where for the events, so i can select only 1 based on criteria but it's not working.

I have tried the following

$city = City::where('name', $event)->first()->event->where('id', 1);

and it's giving me the following error

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

Upvotes: 1

Views: 2704

Answers (3)

Jarek Tkaczyk
Jarek Tkaczyk

Reputation: 81167

Your very example makes no sense, since all you need is:

$eventId = 1;

Event::find($eventId);

In case you wanted to check if that even is related to the city:

Event::where('city_id', $cityId)->find($eventId); // Event model or null

or a bit complicated in this case, but generic solution for any relation type:

Event::whereHas('city', function ($q) use ($cityId) {
   $q->where('id', $cityId);
})->find($eventId); // model or null

And finally, if you used find instead of where:

City::where('name', $event)->first()->event->find(1);
City::where('name', $event)->first()->event()->find(1);

It would return the same Model.

This is because find it does basically the same in the context of a query builder:

City::where('name', $event)->first()->event()->where('id', 1)->first();
// equals to:
City::where('name', $event)->first()->event()->find(1);

but it is also a method of the collection:

$someCollection->find($someId); // returns single Model

Upvotes: 2

Miguel Stevens
Miguel Stevens

Reputation: 9191

Solution

The solution is to use event()-> instead of event-> This query is returning the 1st record of the relationship, Which is what i needed. Thanks everyone!

$city = City::where('name', $event)->first()->event()->where('id', 1)->get();

Upvotes: 0

Chris G
Chris G

Reputation: 7050

If you already have the id (1), you can do something like:

$city = City::where('name', $event)->where('id', 1)->first();

But I think you'd rather want the city_id:

$city = City::where('name', $event)->where('city_id', 3)->first();

Upvotes: 0

Related Questions