An Eloquent Way To Filter Laravel Models And Their Relationships
An Eloquent Way To Filter Laravel Models And Their Relationships
An Eloquent way to filter Eloquent Models and their relationships.
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:
…
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();
}
}
composer require tucker-eric/eloquentfilter
There are a few ways to define the filter a model will use:
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 |
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\\",
This is only required if you want to use the
php artisan model:filtercommand.
In bootstrap/app.php:
$app->register(EloquentFilter\LumenServiceProvider::class);
In bootstrap/app.php:
config(['eloquentfilter.namespace' => "App\\Models\\ModelFilters\\"]);
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
}
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();
}
}
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
Define the filter logic based on the camel cased input key passed to the filter() method.
protected $allowedEmptyFilters = false; on a filter.setup() method is defined it will be called once before any filter methods regardless of input_id is dropped from the end of the input key to define the method so filtering user_id would use the user() methodprotected $drop_id = false; on a filter$this->input() method or a single value by key $this->input($key)$this context 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:
…
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 inside
setup()will be called every timefilter()is called on the model
Any methods defined in the blackist array will not be called by the filter. Those methods are normally used for internal filter logic.
The blacklistMethod() and whitelistMethod() methods can be used to dynamically blacklist and whitelist methods.
In the example above secretMethod() will not be called, even if there is a secret_method key in the input array. In order to call this method it would need to be whitelisted dynamically:
Example:
public function setup()
{
if(Auth::user()->isAdmin()) {
$this->whitelistMethod('secretMethod');
}
}
The Filterable trait also comes with the below query builder helper methods:
| EloquentFilter Method | QueryBuilder Equivalent |
|---|---|
$this->whereLike($column, $string) |
$query->where($column, 'LIKE', '%'.$string.'%') |
$this->whereLike($column, $string, 'or') |
$query->orWhere($column, 'LIKE', '%'.$string.'%') |
$this->whereBeginsWith($column, $string) |
$query->where($column, 'LIKE', $string.'%') |
$this->whereBeginsWith($column, $string, 'or') |
$query->orWhere($column, 'LIKE', $string.'%') |
$this->whereEndsWith($column, $string) |
$query->where($column, 'LIKE', '%'.$string) |
$this->whereEndsWith($column, $string, 'or') |
$query->orWhere($column, 'LIKE', '%'.$string) |
Since these methods are part of the Filterable trait they are accessible from any model that implements the trait without the need to call in the Model's EloquentFilter.
Implement the EloquentFilter\Filterable trait on any Eloquent model:
<?php
namespace App;
use EloquentFilter\Filterable;
use Illuminate\Database\Eloquent\Model;
class User extends Model
{
use Filterable;
//User Class
}
This gives you access to the filter() method that accepts an array of input:
class UserController extends Controller
{
public function index(Request $request)
{
return User::filter($request->all())->get();
}
}
There are two ways to filter by related models. Using the
$relationsarray to define the input to be injected into the related Model's filter. If the related model doesn't have a model filter of it's own or you just want to define how to filter that relationship locally instead of adding the logic to that Model's filter then use therelated()method to filter by a related model that doesn't have a ModelFilter. You can even combine the 2 and define which input fields in the$relationsarray you want to use that Model's filter for as well as use therelated()method to define local methods on that same relation. Both methods nest the filter constraints into the samewhereHas()query on that relation.
For both examples we will use the following models:
A App\User that hasMany App\Client::class:
class User extends Model
{
use Filterable;
public function clients()
{
return $this->hasMany(Client::class);
}
}
And each App\Client belongs to App\Industry::class:
class Client extends Model
{
use Filterable;
public function industry()
{
return $this->belongsTo(Industry::class);
}
public function scopeHasRevenue($query)
{
return $query->where('total_revenue', '>', 0);
}
}
We want to query our users and filter them by the industry and volume potential of their clients that have done revenue in the past.
Input used to filter:
$input = [
'industry' => '5',
'potential_volume' => '10000'
];
Both methods will invoke a setup query on the relationship that will be called EVERY time this relationship is queried. The setup methods signature is {$related}Setup() and is injected with an instance of that relations query builder. For this example let's say when querying users by their clients I only ever want to show agents that have clients with revenue. Without choosing wich method to put it in (because sometimes we may not have all the input and miss the scope all together if we choose the wrong one) and to avoid query duplication by placing that constraint on ALL methods for that relation we call the related setup method in the UserFilter like:
class UserFilter extends ModelFilter
{
public function clientsSetup($query)
{
return $query->hasRevenue();
}
}
This will prepend the query to the clients() relation with hasRevenue() whenever the UserFilter runs any constriants on the clients() relationship. If there are no queries to the clients() relationship then this method will not be invoked.
You can learn more about scopes here
No open issues yet, or sync has not completed.