1

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()
2
  • If it does what you want then it's probably the best method that I can tell. Commented Sep 2, 2014 at 14:15
  • Move your answer from your question to an answer and accept it when you can :) Commented Sep 2, 2014 at 14:24

3 Answers 3

2

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
Sign up to request clarification or add additional context in comments.

Comments

0

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();

2 Comments

Thanks Chris! I found the solution. I had get the event first using event() instead of event and then do the where on that. Thanks!
This is wrong, you don't chain different models queries like that.
0

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();

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.