Laravel Packages

Apply Dynamic Filters to Eloquent Models with the Filterable Package

Published
Apply Dynamic Filters to Eloquent Models with the Filterable Package image

Filterable is a Laravel package by Jerome Thayananthajothy that enhances Laravel queries with adaptable, customizable filters and intelligent caching to improve both performance and functionality.

The main features of this package include:

  • Dynamic Filtering: Apply filters based on request parameters with ease.
  • Caching: Improve performance by caching query results.
  • User-specific Filtering: Easily implement filters that depend on the authenticated user.
  • Custom Filter Methods: Extend the class to add your own filter methods.

Defining Filter classes is at the center of this package, where you can create methods that can apply filtering to Eloquent queries. The package includes a make:filter Artisan command to generate a filter in your app's App\Filters namespace. Here's an example of a filter from the package's README:

namespace App\Filters;
 
use Filterable\Filter;
use Illuminate\Database\Eloquent\Builder;
 
class PostFilter extends Filter
{
protected array $filters = ['status', 'category'];
 
protected function status(string $value): Builder
{
return $this->builder->where('status', $value);
}
 
protected function category(int $value): Builder
{
return $this->builder->where('category_id', $value);
}
}

Given a PostFilter, you can utilize this class in a controller with the Post model to filter models based on the HTTP query params:

public function index(Request $request, PostFilter $filter)
{
// i.e., /posts?status=active&category_id=2
$query = Post::filter($filter);
 
$posts = $request->has('paginate')
? $query->paginate($request->query('per_page', 20))
: $query->get();
 
return response()->json($posts);
}

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

Paul Redmond photo

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

Sponsored

masteringlaravel logo
Laravel Code Review

Get expert guidance in a few days with a Laravel code review

Visit Laravel Code Review

The latest

View all →
CPX: The Composer Package Executor for PHP image

CPX: The Composer Package Executor for PHP

Read article
Laravel AI SDK Adds Human-in-the-Loop Tool Approval image

Laravel AI SDK Adds Human-in-the-Loop Tool Approval

Read article
Pest 5 Released With Test Impact Analysis, Agent Verification, and Evals image

Pest 5 Released With Test Impact Analysis, Agent Verification, and Evals

Read article
Queue-SQL: Run Mass Deletes and Updates Across Parallel Queue Jobs image

Queue-SQL: Run Mass Deletes and Updates Across Parallel Queue Jobs

Read article
Blade Formatting in Laravel Pint image

Blade Formatting in Laravel Pint

Read article
Inertia DevTools Is Now on the Chrome Web Store image

Inertia DevTools Is Now on the Chrome Web Store

Read article