TheShun TheShun - 20 days ago 5
PHP Question

Laravel Eloquent get specific relationship

I'm trying to get the books where the authors are from a specific country, for now my query looks like this :

$books->with('author')->where('country', '=', 'FR');


but the where is applied to books and not to authors

any help ?

Answer

You need to use whereHas() for that. The following code should do the trick:

$country = 'FR';
$books = Book::with('author')->whereHas('author', function($query) use ($country) {
  $query->where('country', '=',  $country);
})->get();

This will give you all books that have a related author, that has country column set to FR.

Comments