Skip to content
Advertisement

Laravel (8.x) Is there a better Eloquent query for this many-to-many filtering problem?

What I have

movies many-to-many stars

movies many-to-many tags

studio one-to-many movies

I pass studio name, star name and/or tag name as optional query strings

What I need

  • Select all movies with tag and star and studio if all 3 are passed as params
  • Select all movies with tag and star if those 2 are passed as params
  • Select all movies with star and studio if those 2 are passed as params
  • Select all movies with tag and studio if those 2 are passed as params
  • Select all movies with tag or star or studio if any one is passed as param
  • Basically, Simplify this query

My Possibly Stuipd code

Advertisement

Answer

I think what you need is this:

This way you only filter your relation if its key is provided.

User contributions licensed under: CC BY-SA
6 People found this is helpful
Advertisement