Courses

Laravel 11 Eloquent: Expert Level

Filter and Search Packages

Summary of this lesson:
- Implementing Spatie Query Builder
- Using Tucker-Eric Eloquent Filter
- Understanding search functionality packages
- Managing advanced filtering capabilities

I want to demonstrate a set of packages related to filtering the data and searching through it, with Eloquent.

First, let's see the packages that will help you run Eloquent queries flexibly, providing the parameters by your users.

It reminds me of the logic of GraphQL. So, GraphQL provides the schema, and then the client of GraphQL tells them what they need, what data, ordering, filters, and other parameters they need.


Spatie: Laravel Query Builder

So a package from Spatie called Laravel-query-builder may transform /users?filter[name]=John URL into an Eloquent query. The user in the URL provides that they need to filter names by John, and the syntax of your query would be:

use Spatie\QueryBuilder\QueryBuilder;
 
$users = QueryBuilder::for(User::class)
->allowedFilters('name')
->get();

Instead of doing User::where('name', 'LIKE', '%John%'), you allow the filter by name. Also, the package allows you to include the relationships automatically and provide the sorting.

In the database, I have eight users and made a query to allow filtering by name and ID and sorting by ID.

$users = QueryBuilder::for(User::class)
->allowedFilters(['name', AllowedFilter::exact('id')])
->allowedSorts('id')
->get();
 
foreach ($users as $user) {
print '<div><strong>' . $user->id . ': ' . $user->name . '</strong>: ' . $user->email . '</div>';
print '<hr />';
}

Without any filter or sorting applied, this is the result in the browser.

For example, let's filter by name for the dr keyword. The result is two users who have the dr keyword in their name.

The Exception will be thrown if you...

The full lesson is only for Premium Members.
Want to access all 28 lessons of this course? (71 min read)

You also get:

  • 69 courses (majority in latest Laravel 11)
  • Premium tutorials
  • Access to repositories
  • Private Discord