TheShun TheShun - 1 year ago 112
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 Source

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.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download