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

nanadjei2's avatar

Query filter by relation

I am creating an application where a building has facilities and I want to make a query to get a building where its facility can be, for example; ["stand-by-generator", "wifi", "swimming-pool"].

The code below returns buildings where facilities are one of these ["stand-by-generator", "wifi", "swimming-pool"] instead of all of these.

This is my query builder. I am actually using a query filter.

 public function apply(Builder $builder, $value): Builder
   {
   // $value = ["stand-by-generator", "wifi", "swimming-pool"];

       return $builder->whereHas('facilities', function ($query) use ($value) {
          $query->whereIn('slug', $value);
       });
   
  }
0 likes
3 replies
Sinnbeck's avatar
Sinnbeck
Best Answer
Level 102

Untested but perhaps you could loop over the $value array and add a new whereHas for each? (no need to return)

foreach ($value as $val) {
       $builder->whereHas('facilities', function ($query) use ($val {
          $query->where('slug', $val);
       });
}
nanadjei2's avatar

Thank you. It worked.

    foreach ($value as $facility) {
        $builder->whereHas('facilities', function ($query) use ($facility) {
            $query->where('slug', $facility);
        });
    }
    return $builder;
Sinnbeck's avatar

@nanadjei2 Happy to help. You can remove the last line from your code. No need to return $builder

Please or to participate in this conversation.