enimiste / laravel-eloquent-filters
Apply filters on laravel eloquent models easy
Installs: 1 600
Dependents: 0
Suggesters: 0
Security: 0
Stars: 24
Watchers: 4
Forks: 4
Open Issues: 0
Requires
- php: >=7.0
- illuminate/database: 5.5.*
- illuminate/http: 5.5.*
- illuminate/support: 5.5.*
This package is auto-updated.
Last update: 2024-11-29 03:49:24 UTC
README
Install
Require this package with composer using the following command:
composer require "enimiste/laravel-eloquent-filters:5.5.*"
Usage :
Use the trait Com\NickelIT\Filterables\Filterable
in your eloquent model.
Create a new class by extending the class Com\NickelIT\Filterables\QueryFilters
and define your custom filters as methods with one argument. Where function names are the filter argument name and the arguments are the value.
Example :
use Illuminate\Database\Eloquent\Builder; class LessonQueryFilters extends QueryFilters { /** * @param string $order * @return Builder */ public function popular($order = 'desc'): Builder { return $this->builder()->orderBy('views', $order); } /** * @param $level * @return Builder */ public function difficulty($level): Builder { return $this->builder()->where('difficulty', $level); } /** * @param string $order * @return Builder */ public function length($order = 'asc'): Builder { return $this->builder()->orderBy('length', $order); } }
With this class we can use the http query string : popular=desc&difficulty=beginner&length
or any combination of these filters. It is up to you to define if you will use AND wheres or OR.
In the controller you can apply these filters like :
class LessonController extends Controller { /** * @param Request $request * @return mixed */ public function index(Request $request) { $bag = new HttpRequestFiltersBag($request); //$bag = new ArrayFiltersBag(['popular' => 'asc', 'difficulty' => 'beginner']); $filter = new LessonQueryFilters($bag); return Lesson::filter($filter)->get();//you can send results to a blade view } }
Thanks to :
https://github.com/laracasts/Dedicated-Query-String-Filtering
License
The Laravel Eloquent Filters is open-sourced software licensed under the MIT license