Weave Code
Code Weaver
Helps Laravel developers discover, compare, and choose open-source packages. See popularity, security, maintainers, and scores at a glance to make better decisions.
Feedback
Share your thoughts, report bugs, or suggest improvements.
Subject
Message

Laravel Filterable Laravel Package

ndnam90/laravel-filterable

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Installation:

    composer require ndnam90/laravel-filterable
    

    Publish the config (if needed):

    php artisan vendor:publish --provider="Ndnam90\Filterable\FilterableServiceProvider"
    
  2. First Use Case: Apply filtering to a model query. Start by defining a filterable trait in your model:

    use Ndnam90\Filterable\Filterable;
    
    class Post extends Model
    {
        use Filterable;
    
        protected $filterable = [
            'title' => 'like',
            'published_at' => 'date',
            'category_id' => '='
        ];
    }
    

    Then filter in your controller:

    $posts = Post::filter(request()->all())->get();
    
  3. Where to Look First:

    • Laracast Tutorial (official guide).
    • config/filterable.php (if published) for customization.
    • app/Models/YourModel.php to define filterable fields.

Implementation Patterns

Common Workflows

  1. Basic Filtering:

    // Controller
    $results = Model::filter(request()->query)->get();
    
    • Automatically applies filters based on $filterable array.
  2. Dynamic Filtering:

    // Override default behavior in model
    public function scopeFilter($query, array $filters)
    {
        return $this->applyFilters($query, $filters);
    }
    
  3. API Integration:

    // API Resource
    public function toArray($request)
    {
        return [
            'data' => $this->filter(request()->query)->get(),
        ];
    }
    
  4. Complex Rules:

    // Custom filter logic
    protected $filterable = [
        'price_range' => function ($query, $value) {
            [$min, $max] = explode(',', $value);
            return $query->whereBetween('price', [$min, $max]);
        }
    ];
    
  5. Form Integration:

    // Blade form
    <form method="GET">
        <input type="text" name="title" placeholder="Search title...">
        <input type="date" name="published_at">
        <button type="submit">Filter</button>
    </form>
    

Integration Tips

  • Validation: Combine with Laravel’s validation to sanitize inputs:
    $validated = request()->validate([
        'title' => 'sometimes|string',
        'published_at' => 'sometimes|date',
    ]);
    $results = Model::filter($validated)->get();
    
  • Pagination: Chain paginate() after filtering:
    $results = Model::filter(request()->query)->paginate(10);
    
  • Relationships: Filter nested relationships by defining them in $filterable:
    protected $filterable = [
        'author.name' => 'like' // Filters author.name column
    ];
    

Gotchas and Tips

Pitfalls

  1. Outdated Package:

    • Last release in 2018 may lack compatibility with newer Laravel versions (e.g., 9.x/10.x).
    • Workaround: Fork the repo or use a modern alternative like spatie/laravel-query-builder.
  2. SQL Injection Risk:

    • Directly passing request()->all() without validation can expose your app.
    • Fix: Always validate/sanitize inputs before filtering.
  3. Performance:

    • Complex filters (e.g., like on large text fields) can slow queries.
    • Tip: Add database indexes to frequently filtered columns:
      php artisan schema:dump
      
      Then manually add indexes in migrations.
  4. Undefined Filters:

    • Accessing non-existent $filterable keys silently fails.
    • Debug: Check config/filterable.php for strict mode or add error handling:
      try {
          $results = Model::filter($filters)->get();
      } catch (\Exception $e) {
          Log::error("Filter error: " . $e->getMessage());
      }
      

Debugging

  • Log Queries: Enable Laravel’s query logging in config/database.php:

    'logging' => true,
    

    Then check logs for generated SQL.

  • Test Filters: Manually test filter logic in Tinker:

    php artisan tinker
    
    $filters = ['title' => 'test'];
    $query = (new Post)->newQuery()->filter($filters);
    dd($query->toSql(), $query->getBindings());
    

Extension Points

  1. Custom Filter Types: Extend the package by adding new filter operators in the service provider:

    // app/Providers/FilterableServiceProvider.php
    public function register()
    {
        Filterable::extend('custom', function ($query, $value) {
            return $query->whereRaw("custom_column LIKE ?", ["%{$value}%"]);
        });
    }
    
  2. Override Default Behavior: Publish and modify the config:

    php artisan vendor:publish --tag=filterable-config
    

    Then customize config/filterable.php (e.g., change default operator).

  3. Macros: Add query builder macros for reusable filter logic:

    use Illuminate\Database\Eloquent\Builder;
    
    Builder::macro('filterByStatus', function ($status) {
        return $this->where('status', $status);
    });
    

    Then use in $filterable:

    protected $filterable = [
        'status' => 'filterByStatus'
    ];
    

Config Quirks

  • Strict Mode: Enable in config/filterable.php to throw exceptions for invalid filters:
    'strict' => env('FILTERABLE_STRICT', false),
    
  • Default Operator: Change the default filter operator (e.g., from = to like):
    'default_operator' => 'like',
    
Weaver

How can I help you explore Laravel packages today?

Conversation history is not saved when not logged in.
Prompt
Add packages to context
No packages found.
daikazu/eloquent-salesforce-objects
unseen-codes/chat
romalytar/yammi-jobs-monitoring-laravel
kisame76/filament-db-table-state
nqxcode/laravel-lucene-search
dpfx/laravel-livewire-wizards
workos/workos-php-laravel
sofa/laravel-global-scope
nawasara/auth-primitives
adhocrat-io/arkhe-main
make-dev/orca-harpoon
itsemon245/lamet
baks-dev/dashboard
amoifr/pickle-panther-bundle
make-dev/orca
dmstr/symfony-system-resources-bundle
dmstr/symfony-job-queue-bundle
dmstr/openapi-json-schema-bundle
dmstr/keycloak-security-bundle
dmstr/doctrine-audit-log-bundle