aidynmakhataev / laravel-filterable
A laravel package to handle filtering by URL query strings
Requires
Requires (Dev)
- orchestra/testbench: ~3.0
- phpunit/phpunit: ~6.0
This package is auto-updated.
Last update: 2024-10-29 05:10:47 UTC
README
A laravel package to handle filtering by URL query strings
Installation
Via Composer
$ composer require aidynmakhataev/laravel-filterable
Usage
- Create a new filter with the following artisan command:
php artisan make:filter UserFilter
This will create App\Http\Filters\UserFilter.php
. You can override the default namespace in config/filterable.php
return [ /* |-------------------------------------------------------------------------- | Filters Configuration |-------------------------------------------------------------------------- | */ // namespace for the generated filters 'namespace' => 'App\Http\Filters' ];
Then, you need to define your filter logic by following this rules:
- Query string without a corresponding filter method are ignored
- Empty strings are ignored
- The value of the each request keys are injected into the corresponding filter method
- You are able to access the eloquent query builder instance by using
$this->builder
Example:
For defining methods for the following url request:
http://yourdomain.com/api/users?gender=male&working=1
You would use the following methods:
namespace App\Http\Filters; use AidynMakhataev\LaravelFilterable\BaseFilter; class UserFilter extends BaseFilter { public function gender($value) { return $this->builder->where('gender', $value); } public function working($value) { return $this->builder->where('is_working', $value); } }
- Add the trait and bind created in step 1 Filter Class to your model.
use AidynMakhataev\LaravelFilterable\Filterable; class User extends Authenticatable { use Filterable; /** * Filters attribute. * * @var array */ protected $filters = \App\Http\Filters\UserFilter::class; }
- Finally, use it in your Controller:
namespace App\Http\Controllers; use Illuminate\Http\Request; use App\User; class UserController extends Controller { public function index(Request $request) { $users = User::filter($request->all())->get(); return response()->json($users); } }
Contributing
Anyone is welcome to contribute. Fork, make your changes, and then submit a pull request.
Security
If you discover any security related issues, please email makataev.7@gmail.com instead of using the issue tracker.
Credits
License
MIT. Please see the license file for more information.