Coder Social home page Coder Social logo

laravel-filters's Introduction

Laravel Eloquent Filter

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!

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.