exenjer/laravel-filters

Easy and convenient filters for your Laravel Eloquent application

This package's canonical repository appears to be gone and the package has been frozen as a result.

2.2.0 2020-01-19 13:28 UTC

This package is auto-updated.

Last update: 2021-10-19 19:43:00 UTC


README

Easy and convenient filters for your Laravel Eloquent application

Installation

Minimum php version to use the package: 7.1
Require this package with composer.

composer require exenjer/laravel-filters

Usage

public function index(Request $request, UserFilter $userFilter)
{
    $users = $userFilter->filter($request->all())
        ->get();
    // OR
    $users = $userFilter->filter($request->all())
        ->paginate();
    // OR
    $users = $userFilter->filter($request->all())
        ->simplePaginate();
        
    // OR
    $users = (new UserFilter())->filter($request->all())
        ->get();
    // ...
}

Configuration

Basic configuration

Create a new class and extend from Filter

class UserFilter extends Filter
{

}

Add filter method:

class UserFilter extends Filter
{
    public function filter(array $request): Filter
    {
        $this->setFilter($this); // Set this class as filter
    
        return $this->apply($request); // Apply filter
    }
}

or use trait for default filter method:

class UserFilter extends Filter
{
    use DefaultFilterSetUp;
}

Specify the model with which the filter will work:

class UserFilter extends Filter
{
    use DefaultFilterSetUp;
    
    protected $model = User::class;
}

Specify the fields to which the filtering will react:

class UserFilter extends Filter
{
    use DefaultFilterSetUp;
    
    protected $model = User::class;
    
    protected $fields = ['name', 'age'];
}

You are ready to write filters!

The following scheme is used for writing filters: Create a method with the following name: 'fieldName' + 'Filter' word for handle all request values except array and 'fieldName' + 'ArrayFilter' for handle arrays.

You may not create methods to filter specific fields. Then the standard methods will be called, details of which are written below.

In the case of using snake_case (e.g. price_from), the name of the method must be in camelCase (priceFromFilter).

Example:

class UserFilter extends Filter
{
    use DefaultFilterSetUp;
    
    protected $model = User::class;
    
    protected $fields = ['name', 'age', 'age_from'];
    
    protected function nameFilter(string $value): void
    {
        $this()->where('name', $value);
    }

    protected function nameArrayFilter(array $value): void
    {
        $this()->whereIn('name', $value);
    }

    protected function ageFromFilter(string $value): void 
    {
        $this()->where('age', '>=', $value);
    }
}

Yes, in order to gain access to the Builder, you need to refer to $this()

Additional configuration

Exclude specific fields

In order to exclude the triggering of standard filters for specific fields from the query, use the array $exclude

protected $exclude = ['id', 'email'];

With trashed

For using all filters withTrashed, set true for $withDeletions property:

protected $withDeletions = true;

Casts

Also, you can cast a value for the resulting values via $casts property:

Note: Supported types: int (integer), bool (boolean), float, double, real, array, object.

Does not work when getting an array

protected $casts = [
    'age' => 'int'
];

Custom builder

If you need to use filtering with predefined eloquent parameters, you can use the setModelBuilder function

public function index(Request $request, UserFilter $userFilter)
{
    $modelBuilder = User::where(...)->with(...);

    $users = $userFilter->setModelBuilder($modelBuilder)
        ->filter($request->all())
        ->get();
}

Dynamic filters

You can dynamically add filters in two ways:

  1. Using the method addFilter()
  2. Using the interface FilterRule and method addFilterClass()

An example implementation of the first method (in UserFilter context):

$this->addFilter('name', function (string $name): void {
    $this()->where('name', $name);
}, function (array $values): void { // For arrays
    $this()->whereIn('name', $values);
});

The implementation of the second method:

Create a class and implement FilterRule interface

class UserNameRuleFilter implements FilterRule
{
    public function handle($value, Builder $builder): void
    {
        $builder->where('name', $value);
    }
 
    public function handleArray(array $values, Builder $builder): void
    {
        $builder->whereIn('name', $values);
    }
}

Add the class from UserFilter instance using the addFilterClass() method

$userFilter->addFilterClass('name', new UserNameRuleFilter());

Default filters

If you have not written filters for a specific field, then the default data handling methods will be called

Their default implementation:

protected function defaultFilterCall(string $field, $value): void
{
    $this()->where($field, $value);
}

protected function defaultArrayFilterCall(string $field, array $values): void
{
    $this()->whereIn($field, $values);
}

You can override them in your filter

class UserFilter extends Filter
{
    use DefaultFilterSetUp;
    
    protected $model = User::class;
    
    protected $fields = ['name', 'age'];
    
    protected function defaultFilterCall(string $field, $value): void
    {
        // Some logic...
    }
    
    protected function defaultArrayFilterCall(string $field, array $values): void
    {
        // Some logic...
    }
}

Thank you

Any pull requests and suggestions are welcome!