Skip to main content

Black Friday 2025! Only until December 1st: coupon FRIDAY25 for 40% off Yearly/Lifetime membership!

Read more here

Filter and Search Packages

Premium
2:28

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 of our courses? (29 h 14 min)

You also get:

54 courses
Premium tutorials
Access to repositories
Private Discord
Get Premium for $129/year or $29/month

Already a member? Login here

Comments & Discussion

No comments yet…