A laravel package to handle filtering by URL query strings
Via Composer
$ composer require aidynmakhataev/laravel-filterable
- 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);
}
}
Anyone is welcome to contribute. Fork, make your changes, and then submit a pull request.
If you discover any security related issues, please email [email protected] instead of using the issue tracker.
MIT. Please see the license file for more information.