jti/laravelfilter

Filter scope for Laravel

0.1 2024-01-14 19:55 UTC

This package is auto-updated.

Last update: 2025-05-15 01:45:34 UTC


README

Latest Version on Packagist Total Downloads Build Status StyleCI

This is where your description should go. Take a look at contributing.md to see a to do list.

Installation

Via Composer

composer require jti/laravelfilter

Usage

  1. Use trait with scope in your Model
<?php

namespace App\Models;

use Illuminate\Contracts\Auth\MustVerifyEmail;
use Illuminate\Foundation\Auth\User as Authenticatable;

class User extends Authenticatable
{
    use Filterable;
}


trait Filterable
{
    /**
     * @param Builder $builder
     * @param LaravelFilter $filter
     */
    public function scopeFilter(Builder $builder, LaravelFilter $filter): void
    {
        $filter->apply($builder);
    }
}
  1. Create your Filter class
class UserFilter extends \JTI\LaravelFilter\LaravelFilter
{

    protected function initBuilder(\Illuminate\Database\Eloquent\Builder $builder): \Illuminate\Database\Eloquent\Builder
    {
        return $this->builder = $builder; // your model builder
    }

    // function name equal key name from array of params
    public function email($email = '')
    {
        if ($email) {
            $this->builder->where('email', '=', $name);
        }
    }
}
}
  1. Use filter in controller for example
class BuilderController extends Controller
{
    public function index()
    {
        $filter = new UserFilter(['email' => 'example@gmail.com']);
        $users = \App\Models\User::query()->filter($filter)->get();
        
        return view('users', compact('users'));
    }

}

Change log

Please see the changelog for more information on what has changed recently.

Testing

composer test

Contributing

Please see contributing.md for details and a todolist.

Security

If you discover any security related issues, please email yuriy.kernytskyi@jointoit.com instead of using the issue tracker.

Credits

License

MIT. Please see the license file for more information.