Laravel Packages

Filter and Search Eloquent Models with the Model Filter Package

Published
Filter and Search Eloquent Models with the Model Filter Package image

Laravel Model Filter offers a simple way to filter and search eloquent models by array parameters and query strings.

Here's a simple example to illustrate exactly how this package works. Given the following filter, you can generate with the provided make:filter command:

namespace App\Models\Filters;

use Lacodix\LaravelModelFilter\Filters\DateFilter;

class CreatedAfterFilter extends DateFilter
{
    public FilterMode $mode = FilterMode::GREATER_OR_EQUAL;

    protected string $field = 'created_at';
}

You can apply the CreatedAfterFilter on a model like the following example:

namespace App\Models;

use App\Models\Filters\CreatedAfterFilter;
use Illuminate\Database\Eloquent\Model;
use Lacodix\LaravelModelFilter\Traits\HasFilters;

class Post extends Model
{
    use HasFilters;

    protected array $filters = [
        CreatedAfterFilter::class,
    ];
}

You can then trigger the filter either programmatically or via query string:

Post::filter(['created_after_filter' => '2023-01-01'])->get();

// Multiple filters
Post::filter([
    'created_after_filter' => '2023-01-01',
    'published_filter' => true,
])->get();

// Or by query string: /posts?created_after_filter=2023-01-01
Post::filterByQueryString()->get();

This package includes many features related to filtering models, such as:

  • Group filtering
  • Filter validation
  • Sorting
  • Searching
  • Date filter type
  • String filter type
  • Select filter type
  • Numeric filter type
  • Boolean filter type
  • Trashed filter type
  • Filtering on relations
  • And more

To get started with this package, check out the official documentation; the source code is also on GitHub at lacodix/laravel-model-filter.

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 →
Slow Job Alerts and Replica Commit IDs in Laravel 13.40 image

Slow Job Alerts and Replica Commit IDs in Laravel 13.40

Read article
Flock: A Free, Native Herd Alternative for Laravel image

Flock: A Free, Native Herd Alternative for Laravel

Read article
Live Props for Real-Time Updates in Inertia.js v3.11 image

Live Props for Real-Time Updates in Inertia.js v3.11

Read article
Cooldown Dependency Policy now in Composer 2.11 image

Cooldown Dependency Policy now in Composer 2.11

Read article
Email Sending and Testing for Laravel in One Account image

Email Sending and Testing for Laravel in One Account

Read article
Decide with Jev: Tie Every AI Check to the Exact Draft image

Decide with Jev: Tie Every AI Check to the Exact Draft

Read article