Home > Net >  Returning filter with relational data to Laravel view
Returning filter with relational data to Laravel view

Time:11-14

Currently my index method works and looks like this:

return view('books.index', [
    'books' => Book::with(['author', 'publisher'])->paginate(15)
]);

But I would like to use filter() to filter results upon request, this is my best shot so far:

return view('books.index', [
    'books' => Book::latest()
        ->filter(request(['search']))
        ->with(['author', 'publisher'])
        ->paginate(15)
        ->withQueryString()
]);

But I keep getting the error:

Call to undefined method Illuminate\Database\Eloquent\Builder::filter()

Any help is greatly appreciated!

CodePudding user response:

In Laravel you have a filter helper. But this works only in collection and not as query builder.

$books = Book::latest()
   ->with(['author', 'publisher'])
   ->paginate(15);

$filteredBooks = $books->filter(function ($value) {
    return $value == request(['search']);
})

dd($filteredBooks);
  • Related