duuany / eloquent-filters
A simplest Eloquent query filter package.
Installs: 582
Dependents: 2
Suggesters: 0
Security: 0
Stars: 1
Watchers: 2
Forks: 1
Open Issues: 0
Type:package
Requires
- illuminate/support: ^6.0|^7.0|^8.0|^9.0
Requires (Dev)
- orchestra/database: ^3.4
- orchestra/testbench: ^3.4
- phpunit/phpunit: ^9.0
README
A simplest Eloquent Model URL query filter package for your Laravel
Instalation
You can install via composer:
Laravel 5.5+
$ composer require duuany/eloquent-filters
###Laravel 5.4 or above
$ composer require duuany/eloquent-filters:1.1
Add the service provider to your config/app.php
Duuany\EloquentFilters\EloquentFiltersServiceProvider::class
Optionally, you can publish config file to override package configuration
$ php artisan vendor:publish --provider="Duuany\EloquentFilters\EloquentFiltersServiceProvider" --tag="config"
Usage
In your model, add the following HasFilters trait
class User extends Model { use HasFilters; }
Create a UserFilter class anywhere in your app folder. Filter classes defines array of applicable filters. For each filter added to array of filters, you need to implement the filter logic.
You can create filters via artisan command
$ php artisan make:filter FilterName
class UserFilter extends EloquentFilters { protected $filters = [ 'order', 'popular', .... ]; protected function order($column) { return $this->builder->orderBy($column, 'desc'); } }
You can pass multiple parameters to your filters, like this:
protected function order($column, $sort = 'desc') { return $this->builder->orderBy($column, $sort); }
When passing more than one paramenter to filter, make sure use a delimiter in your query string.
http://myurl.dev?order=id:asc
The default delimiter its :
, but your can modify overriding the protected $delimiter
property.
Example:
class UserFilter extends EloquentFilters { protected $delimiter = '|'; ... }
In query string...
http://myurl.dev?order=id|asc
... keep in mind, to not use special query strings characters like delimiters.
Magic Calls
Optionally, you can ommit ->builder
:
// this... return $this->builder->orderBy($column, $sort); // can be called like this... return $this->orderBy($column, $sort);
Now in your application you can use the filters as the following:
class UserController extends Controller { public function index(UserFilter $filters) { $users = User::filter($filters)->get(); } }
When the user access the URL http://localhost/?order=id, the order filter will be applied on the User model.
Testing
$ ./vendor/bin/phpunit
Credits
- Jeffrey Way
- Jorge Junior aka jjquady
- Many coffee cups :D
License
The MIT License (MIT). Please see License File for more information.