TheShun TheShun - 7 months ago 70
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 ?


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);

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