ralphmorris / laravel-query-filter
A packages to help create filters to queries based on request parameters
Requires
- php: ^7.1
Requires (Dev)
- orchestra/testbench: 3.7.*
- phpunit/phpunit: ^7.0
This package is auto-updated.
Last update: 2025-05-04 11:10:16 UTC
README
Easily add dedicated filters based on request parameters. Originally came from a great tutorial on Laracasts. After copying it from project to project a few times I've now put it into a little package and added a generator for ease of use.
Installation
You can install the package via composer:
composer require ralphmorris/laravel-query-filter
Usage
To allow a model to be filterable, first add the FilterableTrait to your model.
use Illuminate\Database\Eloquent\Model; use RalphMorris\LaravelQueryFilter\FilterableTrait; class Post extends Model { use FilterableTrait; }
Then to create your filter class run the command below.
php artisan make:filter PostFilters
This will place the filter class under an App\Filters namespace if you are using the default namespace/directory structure. It should look like this.
namespace App\Filters; use RalphMorris\LaravelQueryFilter\QueryFilter; class PostFilters extends QueryFilter { /** * Example * * The request parameter key as the method name. * Passes the parameters value to the method * so we can apply a filter to the query. * * @param mixed $param Value of the request parameter */ public function example_request_param($param) { $this->builder->where('example_request_param', $param); } }
If you wanted to add a filter on the title and author ID, you might do something like this.
namespace App\Filters; use RalphMorris\LaravelQueryFilter\QueryFilter; class PostFilters extends QueryFilter { public function title($title) { $this->builder->where('title', 'like', "%{$title}%"); } public function author($authorId) { $this->builder->where('author_id', $authorId); } }
Finally to add the filters to your query apply filter() query scope in the FilterableTrait to your query and pass the PostFilters class through.
public function index(PostFilters $filters) { $posts = Post::filter($filters)->get(); }
Changelog
Please see CHANGELOG for more information what has changed recently.
Contributing
Please see CONTRIBUTING for details.
Security
If you discover any security related issues, please email ralph@bubblehubsolutions.co.uk instead of using the issue tracker.
Credits
License
The MIT License (MIT). Please see License File for more information.
Laravel Package Boilerplate
This package was generated using the Laravel Package Boilerplate.