Home / Laravel / Advanced Eloquent Query Filtering with Filterable

Advanced Eloquent Query Filtering with Filterable

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 AppModels;
 
use AppHttpFiltersTaskFilter;
use KettasoftFilterableTraitsHasFilterable;
use IlluminateDatabaseEloquentModel;
 
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.

Source: https://laravel-news.com

Tagged:

Leave a Reply

Your email address will not be published. Required fields are marked *