Always in laravel, the filter of database fields and search inside that, it's repetitive work, but you can with use this package create filters very easy.
This work with GET method and query string. When this receives query string, parses this query string to this characters:
Symbol | Do | Usage | Example |
---|---|---|---|
: | separating field from value | Field:value | title:phone |
- | separating range of values | value1-value2 | price:0-100 |
, | separating fields fo filter from sort method | Field:value,sort | title:phone,asc |
By | separating field of sorting from sort method | Field:value,sortByField | title:phone,ascByprice |
composer require hchamran/laravel-filter
(For Laravel <=5.4) Next, you must add the service provider to config/app.php config/app.php
:
'providers' => [
// for laravel 5.4 and below
HChamran\LaravelFilter\Providers\FilterServiceProvider::class,
]
Publish your config file
php artisan vendor:publish
First use filterable in your model:
use Filterable;
Second make filter class with this command for Example:
php artisan make:filter UserFilter
Third, add fields which you want to search inside it for example for products:
public function fields()
{
return [
'title', 'excerpt', 'price'
];
}
And in final just do search with helper:
filter(thisIsField, thisIsValue)
<a href="{{ filter('price', '0-50') }}">Low Price</a>