|
| 1 | +# Laravel Query Filter |
| 2 | + |
| 3 | +In Laravel, it is convenient to write the query filter related to the model in a separate class! |
| 4 | + |
| 5 | +### Installation |
| 6 | + |
| 7 | +``` |
| 8 | +composer require oooiik/laravel-query-filter |
| 9 | +``` |
| 10 | + |
| 11 | +### Usage: |
| 12 | + |
| 13 | +for single use |
| 14 | +```php |
| 15 | +User::filter($validated)->get(); |
| 16 | +``` |
| 17 | +or create a filter |
| 18 | +```php |
| 19 | +$userFilter = User::createFilter(UserFilter::class); |
| 20 | +``` |
| 21 | + |
| 22 | +get a query using a filter |
| 23 | +```php |
| 24 | +$userFilter->apply($validated)->query(); |
| 25 | +``` |
| 26 | +write filter on filter and get a query |
| 27 | +```php |
| 28 | +$userFilter->apply($validated); |
| 29 | +$userFilter->apply($validated_2)->query(); |
| 30 | +``` |
| 31 | +filter cleaning and reuse |
| 32 | +```php |
| 33 | +$userFilter->resetApply($validated_3)->query(); |
| 34 | +``` |
| 35 | + |
| 36 | +In order to use a filter you have to create a new one by the command that is provided by the package: |
| 37 | + |
| 38 | +``` |
| 39 | +php artisan make:filter UserFilter |
| 40 | +``` |
| 41 | +This command will create a directory `Filters` and `UserFilter` class inside. To use the filter method of `User` model use the `Filterable` trait: |
| 42 | + |
| 43 | +```php |
| 44 | +<?php |
| 45 | + |
| 46 | +namespace App\Models; |
| 47 | + |
| 48 | +use Oooiik\LaravelQueryFilter\Traits\Model\Filterable; |
| 49 | + |
| 50 | +class User extends Model |
| 51 | +{ |
| 52 | + use Filterable; |
| 53 | + |
| 54 | +``` |
| 55 | +And set the `defaultFilter` of a model by adding: |
| 56 | + |
| 57 | +```php |
| 58 | +protected $defaultFilter = UserFilter::class; |
| 59 | +``` |
| 60 | +You can create a custom query by creating a new function in the `Filter` class, for example filtering books by publishing date: |
| 61 | +```php |
| 62 | +public function username($username) |
| 63 | +{ |
| 64 | + $this->builder->where('username', $username); |
| 65 | +} |
| 66 | +// $validated = ['username' => 'name'] |
| 67 | +``` |
| 68 | +or filter by relationship: |
| 69 | +```php |
| 70 | +public function role($role) |
| 71 | +{ |
| 72 | + $this->builder->whereHas('role', function($query) use ($role) { |
| 73 | + $query->where('title', $role); |
| 74 | + }) |
| 75 | +} |
| 76 | +// $validated = ['role' => 'admin'] |
| 77 | + |
0 commit comments