Best approach to filter a Collection

Posted 2 years ago by oten

What's your opinion for the best approach to filter a collection based on speed and efficiency terms. Let's say for example that we have a table that contains books. When the user navigates to /books/{slug} I want to print the corresponding book in a h1 tag and all the other books in h3 tags.

Right now my approach is something like this:

public function index($slug) {
    $books = Book::all();

    list($current, $others) = $books->partition(function ($book) {
        return $book->slug ==  $slug;

This works pretty good but I was wondering if there is a more sufficient approach.

Also note that in order to get an attribute you need to first specify the index which is not very handy.

{{ $current[0]->name }}

Please sign in or create an account to participate in this conversation.