intraset / laravel-filter
Filtering Eloquent queries based on HTTP requests.
v0.1.0
2022-12-28 13:19 UTC
Requires
- php: ^8.0
- illuminate/database: ^9.0
This package is auto-updated.
Last update: 2024-10-30 02:16:16 UTC
README
Filtering Eloquent queries based on HTTP requests.
Installation
composer require intraset/laravel-filter
Usage
To apply filters, e.g. on the user model, trait has to be used:
<?php namespace App\Models; use Illuminate\Database\Eloquent\Model; use Intraset\LaravelFilter\HasFilter; class User extends Model { use HasFilter; }
Add filter class to your application to order users by name and filter using ?name=
parameter:
<?php namespace App\Http\Filters; use Illuminate\Database\Eloquent\Builder; use Intraset\LaravelFilter\Filter; class UserFilter extends Filter { /** * Apply filters. * * @param \Illuminate\Database\Eloquent\Builder $builder * @return \Illuminate\Database\Eloquent\Builder */ public function apply(Builder $builder) { parent::apply($builder); $builder->orderBy('name'); return $builder; } /** * Name filter. * * @param string|null $value * @return \Illuminate\Database\Eloquent\Builder */ public function name($value = null) { $this->builder->where('name', $value); return $this->builder; } }
Filter class can then be used to simplify controllers index handler:
public function index(Request $request, UserFilter $filter) { $users = User::filter($filter)->get(); return $users; }
Credits
I got the idea to filter HTTP requests by reading an article written by D. Nagy Gergő and used the code.
License
The MIT License (MIT). Please see License File for more information.