Advanced Eloquent Query Filtering with Filterable

Last updated on by

Advanced Eloquent Query Filtering with Filterable image

Filterable, by Abdalrhman Emad Saad, is a Laravel package that provides a structured approach to Eloquent query filtering. Instead of manual query building in controllers, it uses dedicated filter classes and multiple specialized engines to map HTTP requests to database queries.

The package's core strength lies in its modular engine architecture, allowing developers to choose the filtering style that best fits their frontend requirements.

Basic Usage

To get started, add the HasFilterable trait to your model and optionally bind a default filter class:

namespace App\Models;
 
use App\Http\Filters\TaskFilter;
use Kettasoft\Filterable\Traits\HasFilterable;
use Illuminate\Database\Eloquent\Model;
 
class Task extends Model
{
use HasFilterable;
 
protected $filterable = TaskFilter::class;
}

Now, you can apply filters directly in your controller. The package automatically detects the request parameters:

public function index()
{
// Uses the bound TaskFilter automatically
return Task::filter()->paginate();
}

Multiple Filtering Engines

Filterable includes four built-in engines that handle different request formats:

  • Invokable Engine: Maps request keys to specific methods in your filter class. It supports PHP 8 annotations for casting, validation, and authorization.
  • Ruleset Engine: Handles flat field-operator-value queries for resource lists, such as finding high-stock inventory items (e.g., ?filter[stock][gte]=500&filter[category]=electronics).
  • Expression Engine: Extends the Ruleset engine to support deep Eloquent relationship filtering using dot notation, such as filtering support tickets by the customer's plan level (e.g., ?filter[user.subscription.plan][eq]=premium).
  • Tree Engine: Processes nested AND/OR JSON trees, recursively translating them into Eloquent where and orWhere groups.

PHP 8 Annotations for Filter Logic

The Invokable engine utilizes PHP 8 attributes to handle common tasks like input sanitization and validation directly on the filter methods. This allows you to define constraints like required fields or role-based access at the method level:

class TaskFilter extends Filterable
{
protected $filters = ['title', 'priority', 'due_date'];
 
protected function title(Payload $payload)
{
// Use asLike() for automatic wildcard wrapping
return $this->builder->where('title', 'like', $payload->asLike('both'));
}
 
#[Cast('integer')]
#[In([1, 2, 3])]
protected function priority(Payload $payload)
{
return $this->builder->where('priority_level', $payload->value);
}
 
#[Authorize('manage-tasks')]
#[Required]
#[Date]
protected function due_date(Payload $payload)
{
return $this->builder->whereDate('deadline', '<=', $payload->value);
}
}

Built-in Caching System

The package features an integrated caching system designed specifically for the filter pipeline. It supports tagging, conditional caching, and scoping by user or tenant:

// Cache store inventory for 30 minutes, isolated by branch ID
Product::filter()->cache(1800)->scopeByTenant($branchId)->get();
 
// Only cache results for guest users to reduce load on public listings
Listing::filter()->cacheWhen(auth()->guest(), 3600)->cacheTags(['public_listings'])->get();

Filterable also includes an auto-invalidation feature that can be configured to clear specific cache tags when models are created, updated, or deleted.

CLI and Debugging Tools

Filterable provides several Artisan commands to assist with development and debugging:

  • php artisan filterable:setup: Initial configuration and environment setup.
  • php artisan filterable:make-filter: Generate a new filter class scaffold.
  • php artisan filterable:test: Test a filter class with sample data strings (e.g., --data="status=active").
  • php artisan filterable:inspect: View details about a filter class, including its engines and validation rules.
  • php artisan filterable:discover: Automatically register filter classes within the application.

Installation

You can install the package via Composer:

composer require kettasoft/filterable

The package requires PHP 8.1 or higher and supports Laravel 10 through 12 as of this writing. For more information, you can visit the Filterable documentation or view the source code on GitHub.

Yannick Lyn Fatt photo

Staff Writer at Laravel News and Full stack web developer.

Cube

Laravel Newsletter

Join 40k+ other developers and never miss out on new tips, tutorials, and more.

image
SerpApi

The Web Search API for Your LLM and AI Applications

Visit SerpApi
Laravel Cloud logo

Laravel Cloud

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

Laravel Cloud
SaaSykit: Laravel SaaS Starter Kit logo

SaaSykit: Laravel SaaS Starter Kit

SaaSykit is a Multi-tenant Laravel SaaS Starter Kit that comes with all features required to run a modern SaaS. Payments, Beautiful Checkout, Admin Panel, User dashboard, Auth, Ready Components, Stats, Blog, Docs and more.

SaaSykit: Laravel SaaS Starter Kit
Harpoon: Next generation time tracking and invoicing logo

Harpoon: Next generation time tracking and invoicing

The next generation time-tracking and billing software that helps your agency plan and forecast a profitable future.

Harpoon: Next generation time tracking and invoicing
Acquaint Softtech logo

Acquaint Softtech

Acquaint Softtech offers AI-ready Laravel developers who onboard in 48 hours at $3000/Month with no lengthy sales process and a 100 percent money-back guarantee.

Acquaint Softtech
Tinkerwell logo

Tinkerwell

The must-have code runner for Laravel developers. Tinker with AI, autocompletion and instant feedback on local and production environments.

Tinkerwell
Shift logo

Shift

Running an old Laravel version? Instant, automated Laravel upgrades and code modernization to keep your applications fresh.

Shift
No Compromises logo

No Compromises

Joel and Aaron, the two seasoned devs from the No Compromises podcast, are now available to hire for your Laravel project. ⬧ Flat rate of $9500/mo. ⬧ No lengthy sales process. ⬧ No contracts. ⬧ 100% money back guarantee.

No Compromises
PhpStorm logo

PhpStorm

The go-to PHP IDE with extensive out-of-the-box support for Laravel and its ecosystem.

PhpStorm
Lucky Media logo

Lucky Media

Get Lucky Now - the ideal choice for Laravel Development, with over a decade of experience!

Lucky Media
Kirschbaum logo

Kirschbaum

Providing innovation and stability to ensure your web application succeeds.

Kirschbaum

The latest

View all →
Vocalizer: Local Text-to-Speech for PHP image

Vocalizer: Local Text-to-Speech for PHP

Read article
Build a Laravel Scout Search Endpoint With the HTTP QUERY Method image

Build a Laravel Scout Search Endpoint With the HTTP QUERY Method

Read article
Enforce Per-Action Waiting Periods in Laravel with Cooldown image

Enforce Per-Action Waiting Periods in Laravel with Cooldown

Read article
First-Party Image Processing in Laravel 13.20 image

First-Party Image Processing in Laravel 13.20

Read article
Laravel Legacy Bridge: Carry Authenticated Sessions from a Legacy App into Laravel image

Laravel Legacy Bridge: Carry Authenticated Sessions from a Legacy App into Laravel

Read article
Laravel Quota: Usage Budgets for Calendar Periods image

Laravel Quota: Usage Budgets for Calendar Periods

Read article