Provides a composable interface for data filtering with query strings
mykeels/laravel-filters is a Laravel package for provides a composable interface for data filtering with query strings.
It currently has 16 GitHub stars and 1.521 downloads on Packagist.
Install it with composer require mykeels/laravel-filters.
Discover more Laravel packages by mykeels
or browse all Laravel packages to compare alternatives.
Last updated
Imagine that ...
This URL:
/users?name=myk&age=21&company=rick-and-morty&sort_age=desc
automatically knew to filter the DB query by responding with users that have their
myk21rick-and-mortyand order the records by age in descending order, all without you having to write boilerplate code 😱.
Or that you could automatically include a relationship for a model by adding a ?with_relationship to the URL 😍, like:

Hold your horses 😜, I'm about to show you how.
composer require mykeels/laravel-filters in your terminal to pull the package in.FilterableTrait like:<?php
use Mykeels\Filters\Traits\FilterableTrait;
class User {
use FilterableTrait;
...
}
UserFilter<?php
namespace App\Filters;
use App\User;
use Mykeels\Filters\BaseFilters;
use Illuminate\Http\Request;
use Carbon\Carbon;
class UserFilters extends BaseFilters
{
public function name($term) {
return $this->builder->where('users.name', 'LIKE', "%$term%");
}
public function company($term) {
return $this->builder->whereHas('company', function ($query) use ($term) {
return $query->where('name', 'LIKE', "%$term%");
});
}
public function age($term) {
$year = Carbon::now()->subYear($age)->format('Y');
return $this->builder->where('dob', '>=', "$year-01-01")->where('dob', '<=', "$year-12-31");
}
public function sort_age($type = null) {
return $this->builder->orderBy('dob', (!$type || $type == 'asc') ? 'desc' : 'asc');
}
}
Note how the name of each method maps to the key of each query string in
/users?name=myk&age=21&company=rick-and-morty&sort_age=desc, and the parameters of the methods map to the values.
UserFilters in your controller 😍, like:<?php
namespace App\Http\Controllers;
use App\User;
use App\Filters\UserFilters;
class UserController extends Controller {
public function index(Request $request, UserFilters $filters)
{
return User::filter($filters)->get();
}
}
That's all! 💃
Now, you can execute your app, and use variations of the query strings that your filters allow for. 🔥🔥🔥