phplaraveleloquentdistinct

Get a distinct list of all related model instances in Eloquent


I have two Eloquent models (say: Books and Authors) which have a one-to-many-relation (one Author can have many Books, each Book has exactly one Author). The database also contains Authors which have no Book at all. I would like to retrieve a list of all Authors which have a Book - whitout having duplicate authors.

Currently I loop over all Book instances and add the Author to the list if it is not yet in the list:

$books = Books::all();
$list = [];
foreach ($books as $book) {
    if (! in_array($book->author, $list) ) {
        array_push($list, $book->author);
    }
}

I wonder whether there is a smarter way to get this, i.e. a way, which reuduces the number of database queries.


Solution

  • I would like to retrieve a list of all Authors which have a Book - whitout having duplicate authors

    Use the has() method:

    $authorsWithBooks = Author::has('books')->get();