Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

DavidBuchukuri's avatar

How to filter a query based on columns from foreign table?

I have movies and quotes table. quote has foreign key which references movie id. I need to write a query which gets a quote where movie name = 'foobar'. when i write a query like this

Quote::with('movie')->find(16)

I get back result

{
     body: "quote",
     movie_id: 1,
     movie: App\Models\Movie {#4594
       id: 1,
       name: "Jairo Abbott",
       year: 2005,
	}	
}

I tried to filter like this

Quote::with('movie')->where('movie.name', 'like', '%l%')->get()

but I am getting errors

0 likes
2 replies
DavidBuchukuri's avatar

@MichalOravec thanks, that worked. I read further and found out that there is a method whereRelation, which allows us to write this in more elegant way

Please or to participate in this conversation.