Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Laravel query builder - how to filter by relationship field

Tags:

laravel

For the sake of example, say I have the following, where there is a relationship set up for each person having one hat.

$people = People::join('hat')->get();

How do I filter my results to only give me the people whose hats are red?

I have tried,

$people = People::join('hat')
    ->where('hat.colour', 'red')
    ->get();    

...but no luck so far.

Cheers

like image 495
Steve Avatar asked Dec 19 '25 12:12

Steve


1 Answers

Use whereHas():

$people = People::whereHas('hat', function($query) {
    $query->where('colour', 'red');
})->get(); 
like image 129
Jonas Staudenmeir Avatar answered Dec 23 '25 15:12

Jonas Staudenmeir



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!