I want to filter this $authors
collection.
$authors = Author::get();
In my view, I need to show how many books an author is related.
I use .each() to merge the count
to $authors
and return it to where it was called.
return $authors->each(function($author, $key){
$author->count = Author::findOrFail($author->id)->books()->count();
});
Question is "How can I remove/filter if an author have not wrriten any of a book(count <= 0)?"
I tried this is and it failed.
return $authors->each(function($author, $key){
$author->count = Author::findOrFail($author->id)->books()->count();
$author->filter(function($author, $key){
return $author->count <= 0;
})
});
You should use withCount()
to avoid N+1 and performance problems:
$authors = Author::withCount('books')->get();
In a Blade view, you'll be able to do:
$author->books_count
If you want to count the number of results from a relationship without actually loading them you may use the
withCount
method, which will place a{relation}_count
column on your resulting models.
https://laravel.com/docs/5.4/eloquent-relationships#counting-related-models