sundrigast/laravel-filters

Convenient and simple filters for your Laravel Eloquent application

dev-main 2021-04-02 09:42 UTC

This package is auto-updated.

Last update: 2024-09-29 06:02:57 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 sundrigast/laravel-filters

Usage

public function index(UserFilter $filter)
{
    return User::filter($filter)
      ->paginate();
}

Configuration

Basic configuration

Create a new class and extend from QueryFilter

class UserFilter extends QueryFilter
{

}

Use trait for default filter method in your model:

class User extends Model
{
    use HasFilters;
}

You are ready to write filters!

The following scheme is used for writing filters: Create a method with the following name which corresponds to the field for the filter.

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
{       
    protected function name(string $value)
    {
        return $this->builder->where('name', $value);
    }

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

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

Thank you

Any pull requests and suggestions are welcome!