laraditz / model-filter by raditzfarhan

A simple eloquent model filter.
72
0
2
Package Data
Maintainer Username: raditzfarhan
Maintainer Contact: raditzfarhan@gmail.com (Raditz Farhan)
Package Create Date: 2021-04-01
Package Last Update: 2023-04-14
Language: PHP
License: MIT
Last Refreshed: 2024-04-12 03:13:46
Package Statistics
Total Downloads: 72
Monthly Downloads: 0
Daily Downloads: 0
Total Stars: 0
Total Watchers: 2
Total Forks: 0
Total Open Issues: 0

Laravel Model Filter

Latest Stable Version Total Downloads License StyleCI

A simple eloquent model filter for Laravel and Lumen.

Installation

Via Composer

$ composer require laraditz/model-filter

Configuration

Add filterable trait to your model as below snippet:

use Laraditz\ModelFilter\Filterable;

class User extends Model implements AuthenticatableContract, AuthorizableContract
{
    use Filterable;
    ...
}

Create filter class under the App/Filters folder with <model_name>Filter format. For example for User model, you will need to create UserFilter class.

Below snippet shows how the UserFilter could look like:

namespace App\Filters;

use Laraditz\ModelFilter\Filter;
use Illuminate\Database\Eloquent\Builder;

class UserFilter extends Filter
{
    public function name(string $value)
    {
        $this->where('name', 'LIKE', $value);
    }

    public function email(string $value)
    {
        $this->where('email', 'LIKE', "%$value%");
    }

    // Filter relationship
    public function rank($value)
    {
        $this->whereHas('rank', function (Builder $query) use ($value) {
            $query->where('level', 'like', $value);
        });
    }
}

If you want to have more control on which attributes can be filtered, you can add filterable array to you model:


protected $filterable = [
    'name', 'email'
];

Usage

In your controller, call filter method and pass the input data to use the filter that you have created.

$users = User::filter($request->all())->get();

Your request query strings could look like this.

/users?name=farhan&rank=novice

You could also pass sort param to apply sorting for your result.

/users?name=farhan&rank=novice&sort=name,level

Sort desc by adding - symbol in front of the field name

/users?name=farhan&rank=novice&sort=-name,level

That's it!

Credits

License

MIT. Please see the license file for more information.