Laravel Packages

Advanced Eloquent Model Filters

Published
Advanced Eloquent Model Filters image

Advanced Laravel Model Filters is a package that gives you fine-grained control and reusable classes you can use to filter Eloquent models. The readme has an example where perhaps you'd like to filter by the name column:

$filters = EloquentFilters::make([
new NameFilter($request->name)
]);
 
$products = Product::filter($filters)->get();

The NameFilter class is a reusable filter you can reuse wherever you need to filter by name:

use Pricecurrent\LaravelEloquentFilters\AbstractEloquentFilter;
use Illuminate\Database\Eloquent\Builder;
 
class NameFilter extends AbstractEloquentFilter
{
protected $name;
 
public function __construct($name)
{
$this->name = $name;
}
 
public function apply(Builder $builder): Builder
{
return $query->where('name', 'like', "{$this->name}%");
}
}

The NameFilter is now reusable, as shown in the following example being used in tandem with the User model. This code example also demonstrates how you can chain methods on filter() as if it was an Eloquent builder instance:

$filters = EloquentFilters::make([
new NameFilter($request->user_name)
]);
 
$products = User::query()
->filter($filters)
->limit(10)
->latest()
->get();

You can learn more about this package, get full installation instructions, and view the source code on GitHub.


This package was submitted to our Laravel News Links section. Links is a place the community can post packages and tutorials around the Laravel ecosystem. Follow along on Twitter @LaravelLinks

Paul Redmond photo

Staff writer at Laravel News. Full stack web developer and author.

Sponsored

laravelcloud logo
Laravel Cloud

Easily create and manage your servers and deploy your Laravel applications in seconds.

Visit Laravel Cloud

The latest

View all →
Building EasyReply: How We Used Laravel to Unify Customer Support image

Building EasyReply: How We Used Laravel to Unify Customer Support

Read article
PostgreSQL Monitoring and Schema Linting for Laravel with Vacuum image

PostgreSQL Monitoring and Schema Linting for Laravel with Vacuum

Read article
PayZephyr: One Payment API for Stripe, Paystack, and PayPal image

PayZephyr: One Payment API for Stripe, Paystack, and PayPal

Read article
Bifrost Turns One With AI Builds and New Workflows image

Bifrost Turns One With AI Builds and New Workflows

Read article
Preview Blade Templates in macOS Finder with Quick Blade image

Preview Blade Templates in macOS Finder with Quick Blade

Read article
Artisan Debugging Commands in Laravel Telescope 5.24.0 image

Artisan Debugging Commands in Laravel Telescope 5.24.0

Read article