EloquentFilter
An Eloquent Way To Filter Laravel Models And Their Relationships
Install / Use
/learn @Tucker-Eric/EloquentFilterREADME
Eloquent Filter
An Eloquent way to filter Eloquent Models and their relationships.
Introduction
Lets say we want to return a list of users filtered by multiple parameters. When we navigate to:
/users?name=er&last_name=&company_id=2&roles[]=1&roles[]=4&roles[]=7&industry=5
$request->all() will return:
[
'name' => 'er',
'last_name' => '',
'company_id' => '2',
'roles' => ['1','4','7'],
'industry' => '5'
]
To filter by all those parameters we would need to do something like:
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Http\Requests;
use App\User;
class UserController extends Controller
{
public function index(Request $request)
{
$query = User::where('company_id', $request->input('company_id'));
if ($request->has('last_name'))
{
$query->where('last_name', 'LIKE', '%' . $request->input('last_name') . '%');
}
if ($request->has('name'))
{
$query->where(function ($q) use ($request)
{
return $q->where('first_name', 'LIKE', $request->input('name') . '%')
->orWhere('last_name', 'LIKE', '%' . $request->input('name') . '%');
});
}
$query->whereHas('roles', function ($q) use ($request)
{
return $q->whereIn('id', $request->input('roles'));
})
->whereHas('clients', function ($q) use ($request)
{
return $q->whereHas('industry_id', $request->input('industry'));
});
return $query->get();
}
}
To filter that same input With Eloquent Filters:
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Http\Requests;
use App\User;
class UserController extends Controller
{
public function index(Request $request)
{
return User::filter($request->all())->get();
}
}
Configuration
Install Through Composer
composer require tucker-eric/eloquentfilter
There are a few ways to define the filter a model will use:
- Use EloquentFilter's Default Settings
- Use A Custom Namespace For All Filters
- Define A Model's Default Filter
- Dynamically Select A Model's Filter
Default Settings
The default namespace for all filters is App\ModelFilters\ and each Model expects the filter classname to follow the {$ModelName}Filter naming convention regardless of the namespace the model is in. Here is an example of Models and their respective filters based on the default naming convention.
|Model|ModelFilter|
|-----|-----------|
|App\User|App\ModelFilters\UserFilter|
|App\FrontEnd\PrivatePost|App\ModelFilters\PrivatePostFilter|
|App\FrontEnd\Public\GuestPost|App\ModelFilters\GuestPostFilter|
Laravel
With Configuration File (Optional)
Registering the service provider will give you access to the
php artisan model:filter {model}command as well as allow you to publish the configuration file. Registering the service provider is not required and only needed if you want to change the default namespace or use the artisan command
After installing the Eloquent Filter library, register the EloquentFilter\ServiceProvider::class in your config/app.php configuration file:
'providers' => [
// Other service providers...
EloquentFilter\ServiceProvider::class,
],
Copy the package config to your local config with the publish command:
php artisan vendor:publish --provider="EloquentFilter\ServiceProvider"
In the config/eloquentfilter.php config file. Set the namespace your model filters will reside in:
'namespace' => "App\\ModelFilters\\",
Lumen
Register The Service Provider (Optional)
This is only required if you want to use the
php artisan model:filtercommand.
In bootstrap/app.php:
$app->register(EloquentFilter\LumenServiceProvider::class);
Change The Default Namespace
In bootstrap/app.php:
config(['eloquentfilter.namespace' => "App\\Models\\ModelFilters\\"]);
Define The Default Model Filter (optional)
The following is optional. If no
modelFiltermethod is found on the model the model's filter class will be resolved by the default naming conventions
Create a public method modelFilter() that returns $this->provideFilter(Your\Model\Filter::class); in your model.
<?php
namespace App;
use EloquentFilter\Filterable;
use Illuminate\Database\Eloquent\Model;
class User extends Model
{
use Filterable;
public function modelFilter()
{
return $this->provideFilter(\App\ModelFilters\CustomFilters\CustomUserFilter::class);
}
//User Class
}
Dynamic Filters
You can define the filter dynamically by passing the filter to use as the second parameter of the filter() method. Defining a filter dynamically will take precedent over any other filters defined for the model.
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Http\Requests;
use App\User;
use App\ModelFilters\Admin\UserFilter as AdminFilter;
use App\ModelFilters\User\UserFilter as BasicUserFilter;
use Auth;
class UserController extends Controller
{
public function index(Request $request)
{
$userFilter = Auth::user()->isAdmin() ? AdminFilter::class : BasicUserFilter::class;
return User::filter($request->all(), $userFilter)->get();
}
}
Generating The Filter
Only available if you have registered
EloquentFilter\ServiceProvider::classin the providers array in your `config/app.php'
You can create a model filter with the following artisan command:
php artisan model:filter User
Where User is the Eloquent Model you are creating the filter for. This will create app/ModelFilters/UserFilter.php
The command also supports psr-4 namespacing for creating filters. You just need to make sure you escape the backslashes in the class name. For example:
php artisan model:filter AdminFilters\\User
This would create app/ModelFilters/AdminFilters/UserFilter.php
Usage
Defining The Filter Logic
Define the filter logic based on the camel cased input key passed to the filter() method.
- Empty strings and null values are ignored by default.
- Empty strings and values can be configured not to be ignored by setting
protected $allowedEmptyFilters = false;on a filter.
- Empty strings and values can be configured not to be ignored by setting
- If a
setup()method is defined it will be called once before any filter methods regardless of input _idis dropped from the end of the input key to define the method so filteringuser_idwould use theuser()method- Can be changed with by definining
protected $drop_id = false;on a filter
- Can be changed with by definining
- Input without a corresponding filter method are ignored
- The value of the key is injected into the method
- All values are accessible through the
$this->input()method or a single value by key$this->input($key) - All Eloquent Builder methods are accessible in
$thiscontext in the model filter class.
To define methods for the following input:
[
'company_id' => 5,
'name' => 'Tuck',
'mobile_phone' => '888555'
]
You would use the following methods:
use EloquentFilter\ModelFilter;
class UserFilter extends ModelFilter
{
protected $blacklist = ['secretMethod'];
// This will filter 'company_id' OR 'company'
public function company($id)
{
return $this->where('company_id', $id);
}
public function name($name)
{
return $this->where(function($q) use ($name)
{
return $q->where('first_name', 'LIKE', "%$name%")
->orWhere('last_name', 'LIKE', "%$name%");
});
}
public function mobilePhone($phone)
{
return $this->where('mobile_phone', 'LIKE', "$phone%");
}
public function setup()
{
$this->onlyShowDeletedForAdmins();
}
public function onlyShowDeletedForAdmins()
{
if(Auth::user()->isAdmin())
{
$this->withTrashed();
}
}
public function secretMethod($secretParameter)
{
return $this->where('some_column', true);
}
}
Note: In the above example if you do not want
_iddropped from the end of the input you can setprotected $drop_id = falseon your filter class. Doing this would allow you to have acompany()filter method as well as acompanyId()filter method.
Note: In the above example if you do not want
mobile_phoneto be mapped tomobilePhone()you can setprotected $camel_cased_methods = falseon your filter class. Doing this would allow you to have amobile_phone()filter method instead ofmobilePhone(). By default,mobilePhone()filter method can be called thanks to one of the following input key:mobile_phone,mobilePhone,mobile_phone_id
Note: In the example above all methods
Related Skills
node-connect
346.4kDiagnose OpenClaw node connection and pairing failures for Android, iOS, and macOS companion apps
frontend-design
107.2kCreate distinctive, production-grade frontend interfaces with high design quality. Use this skill when the user asks to build web components, pages, or applications. Generates creative, polished code that avoids generic AI aesthetics.
openai-whisper-api
346.4kTranscribe audio via OpenAI Audio Transcriptions API (Whisper).
qqbot-media
346.4kQQBot 富媒体收发能力。使用 <qqmedia> 标签,系统根据文件扩展名自动识别类型(图片/语音/视频/文件)。
