• Reading time ~ 1 min
  • 02.03.2023

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.

Comments

No comments yet
Yurij Finiv

Yurij Finiv

Full stack

ABOUT

Professional Fullstack Developer with extensive experience in website and desktop application development. Proficient in a wide range of tools and technologies, including Bootstrap, Tailwind, HTML5, CSS3, PUG, JavaScript, Alpine.js, jQuery, PHP, MODX, and Node.js. Skilled in website development using Symfony, MODX, and Laravel. Experience: Contributed to the development and translation of MODX3 i...

About author CrazyBoy49z
WORK EXPERIENCE
Contact
Ukraine, Lutsk
+380979856297