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.
You can install the package via composer:
composer require ralphmorris/laravel-query-filter
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();
}
Please see CHANGELOG for more information what has changed recently.
Please see CONTRIBUTING for details.
If you discover any security related issues, please email [email protected] instead of using the issue tracker.
The MIT License (MIT). Please see License File for more information.
This package was generated using the Laravel Package Boilerplate.