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

Filter Bundle Laravel Package

cannibal/filter-bundle

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Installation

    composer require cannibal/filter-bundle
    

    Add to config/app.php under providers:

    Cannibal\FilterBundle\FilterBundle::class,
    

    Publish the config (if needed):

    php artisan vendor:publish --provider="Cannibal\FilterBundle\FilterBundle"
    
  2. Basic Usage Define a filterable resource (e.g., User model) with a Filterable trait or interface:

    use Cannibal\FilterBundle\Contracts\Filterable;
    
    class User implements Filterable
    {
        // ...
    }
    
  3. First Filter Request Add filters to a request (e.g., GET /users?filter[name]=John&filter[active]=true). The bundle automatically parses and applies them via a FilterManager.


Implementation Patterns

1. Defining Filters

Use annotations or YAML/XML to define filter rules for a resource:

# config/filters/user.yaml
filters:
  name:
    type: string
    operator: contains
  active:
    type: boolean
    operator: eq
  created_at:
    type: date
    operator: between

2. Applying Filters in Controllers

Leverage the FilterManager to process requests:

use Cannibal\FilterBundle\FilterManager;

class UserController extends Controller
{
    public function index(FilterManager $filterManager)
    {
        $users = $filterManager->apply(
            User::query(),
            request()->all()
        );
        return $users;
    }
}

3. Custom Filter Operators

Extend the bundle by creating custom operators:

use Cannibal\FilterBundle\Contracts\FilterOperator;

class CustomOperator implements FilterOperator
{
    public function apply($query, $field, $value)
    {
        return $query->where($field, 'like', "%{$value}%");
    }
}

Register in config/filters.php:

'operators' => [
    'custom' => \App\Filters\CustomOperator::class,
],

4. API Integration

Use the FilterRequest middleware to parse and validate filters:

use Cannibal\FilterBundle\Http\Middleware\FilterRequest;

$router->middleware(FilterRequest::class);

5. Dynamic Filtering

For dynamic collections (e.g., Eloquent queries), inject the FilterManager into services:

class UserService
{
    public function __construct(private FilterManager $filterManager) {}

    public function getFilteredUsers(array $filters)
    {
        return $this->filterManager->apply(
            User::query(),
            $filters
        );
    }
}

Gotchas and Tips

Pitfalls

  1. Naming Conventions

    • Filters must follow filter[field]=value format in requests. Deviations (e.g., ?name=John) won’t work unless customized.
  2. Query Builder Compatibility

    • Complex operators (e.g., between) may require raw SQL or custom implementations for non-Eloquent queries.
  3. Caching Issues

    • Filters are applied per-request. Avoid caching filtered queries unless explicitly handling filter parameters in cache keys.
  4. Type Safety

    • The bundle assumes type casting (e.g., boolean, date). Invalid types (e.g., "true" for a boolean field) may cause errors.

Debugging Tips

  • Log Filter Inputs Add middleware to log raw filter requests:
    request()->all()['filter'] ?? [];
    
  • Validate Config Ensure config/filters.php includes all required fields. Missing definitions will silently ignore filters.

Extension Points

  1. Custom Filter Sources Override FilterManager to support non-request sources (e.g., GraphQL inputs):
    $manager->apply(User::query(), $graphqlInput['filters']);
    
  2. Operator Prioritization Extend FilterManager to reorder or skip operators dynamically.
  3. Localization Add i18n support for operator labels (e.g., contains, between) by overriding the FilterBuilder.

Performance

  • Batch Processing For large datasets, use cursor() or chunk() after filtering to avoid memory issues.
  • Lazy Loading Prefer ->get() over ->all() when filters are applied to collections.

Testing

  • Mock FilterManager In unit tests, mock the manager to return stubbed queries:
    $manager->shouldReceive('apply')
            ->once()
            ->andReturn(User::factory()->count(2));
    
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.
helgesverre/toon
symfony/ai-mate
f1monkey/eve-esi-bundle
f-froehlich/symfony-validator
f-froehlich/api
ezsystems/templated-uri-bundle
ezsystems/stash-bundle
ezsystems/share-buttons-bundle
ezsystems/privacy-cookie-bundle
ezsystems/payment-paypal-bundle
ezsystems/payment-core-bundle
ezsystems/job-queue-bundle
ezsystems/hybrid-platform-ui
ezsystems/ezmigrationbundle
ezsystems/ezcommerce-econtent-installer
ezsystems/comment-bundle
ezsystems/apache-tika-bundle
ezar101/easyadmin-trix-extension-bundle
eyerim/oauth2-azure-bundle
exu/bundle-skeleton