{"id":15028881,"url":"https://github.com/tucker-eric/eloquentfilter","last_synced_at":"2025-05-12T15:19:08.508Z","repository":{"id":39160045,"uuid":"53163405","full_name":"Tucker-Eric/EloquentFilter","owner":"Tucker-Eric","description":"An Eloquent Way To Filter Laravel Models And Their Relationships","archived":false,"fork":false,"pushed_at":"2025-04-11T15:43:41.000Z","size":374,"stargazers_count":1750,"open_issues_count":0,"forks_count":126,"subscribers_count":43,"default_branch":"master","last_synced_at":"2025-04-23T17:12:16.697Z","etag":null,"topics":["dynamic-filters","eloquent","eloquent-filters","eloquent-models","eloquentfilter","filter","filter-logic","laravel","laravel-filter","model-filters","query","relation-filter"],"latest_commit_sha":null,"homepage":"http://tucker-eric.github.io/EloquentFilter","language":"PHP","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":"mit","status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/Tucker-Eric.png","metadata":{"files":{"readme":"README.md","changelog":null,"contributing":null,"funding":null,"license":"LICENSE.txt","code_of_conduct":"CODE_OF_CONDUCT.md","threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null,"governance":null,"roadmap":null,"authors":null,"dei":null,"publiccode":null,"codemeta":null}},"created_at":"2016-03-04T20:27:24.000Z","updated_at":"2025-04-23T13:41:45.000Z","dependencies_parsed_at":"2023-02-19T20:35:26.470Z","dependency_job_id":"d15a38db-a4cb-444b-89f3-fd8c454c5b92","html_url":"https://github.com/Tucker-Eric/EloquentFilter","commit_stats":{"total_commits":183,"total_committers":23,"mean_commits":7.956521739130435,"dds":0.4808743169398907,"last_synced_commit":"faaad783b7f23af7ba7e23baaa56d71af51504a9"},"previous_names":[],"tags_count":39,"template":false,"template_full_name":null,"repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/Tucker-Eric%2FEloquentFilter","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/Tucker-Eric%2FEloquentFilter/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/Tucker-Eric%2FEloquentFilter/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/Tucker-Eric%2FEloquentFilter/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/Tucker-Eric","download_url":"https://codeload.github.com/Tucker-Eric/EloquentFilter/tar.gz/refs/heads/master","host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":250477810,"owners_count":21437049,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2022-07-04T15:15:14.044Z","host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":["dynamic-filters","eloquent","eloquent-filters","eloquent-models","eloquentfilter","filter","filter-logic","laravel","laravel-filter","model-filters","query","relation-filter"],"created_at":"2024-09-24T20:09:16.116Z","updated_at":"2025-04-23T17:12:24.640Z","avatar_url":"https://github.com/Tucker-Eric.png","language":"PHP","readme":"# Eloquent Filter\n\n[![Latest Stable Version](https://poser.pugx.org/tucker-eric/eloquentfilter/v/stable)](https://packagist.org/packages/tucker-eric/eloquentfilter)\n[![Total Downloads](https://poser.pugx.org/tucker-eric/eloquentfilter/downloads)](https://packagist.org/packages/tucker-eric/eloquentfilter)\n[![Daily Downloads](https://poser.pugx.org/tucker-eric/eloquentfilter/d/daily)](https://packagist.org/packages/tucker-eric/eloquentfilter)\n[![License](https://poser.pugx.org/tucker-eric/eloquentfilter/license)](https://packagist.org/packages/tucker-eric/eloquentfilter)\n[![StyleCI](https://styleci.io/repos/53163405/shield)](https://styleci.io/repos/53163405/)\n[![PHPUnit Status](https://github.com/Tucker-Eric/EloquentFilter/workflows/PHPUnit/badge.svg?branch=master)](https://github.com/Tucker-Eric/EloquentFilter/actions?query=branch%3Amaster)\n\nAn Eloquent way to filter Eloquent Models and their relationships.\n\n## Introduction\nLets say we want to return a list of users filtered by multiple parameters. When we navigate to:\n\n`/users?name=er\u0026last_name=\u0026company_id=2\u0026roles[]=1\u0026roles[]=4\u0026roles[]=7\u0026industry=5`\n\n`$request-\u003eall()` will return:\n\n```php\n[\n    'name'       =\u003e 'er',\n    'last_name'  =\u003e '',\n    'company_id' =\u003e '2',\n    'roles'      =\u003e ['1','4','7'],\n    'industry'   =\u003e '5'\n]\n```\n\nTo filter by all those parameters we would need to do something like:\n\n```php\n\u003c?php\n\nnamespace App\\Http\\Controllers;\n\nuse Illuminate\\Http\\Request;\nuse App\\Http\\Requests;\nuse App\\User;\n\nclass UserController extends Controller\n{\n\n    public function index(Request $request)\n    {\n        $query = User::where('company_id', $request-\u003einput('company_id'));\n\n        if ($request-\u003ehas('last_name'))\n        {\n            $query-\u003ewhere('last_name', 'LIKE', '%' . $request-\u003einput('last_name') . '%');\n        }\n\n        if ($request-\u003ehas('name'))\n        {\n            $query-\u003ewhere(function ($q) use ($request)\n            {\n                return $q-\u003ewhere('first_name', 'LIKE', $request-\u003einput('name') . '%')\n                    -\u003eorWhere('last_name', 'LIKE', '%' . $request-\u003einput('name') . '%');\n            });\n        }\n\n        $query-\u003ewhereHas('roles', function ($q) use ($request)\n        {\n            return $q-\u003ewhereIn('id', $request-\u003einput('roles'));\n        })\n            -\u003ewhereHas('clients', function ($q) use ($request)\n            {\n                return $q-\u003ewhereHas('industry_id', $request-\u003einput('industry'));\n            });\n\n        return $query-\u003eget();\n    }\n\n}\n```\n\nTo filter that same input With Eloquent Filters:\n\n```php\n\u003c?php\n\nnamespace App\\Http\\Controllers;\n\nuse Illuminate\\Http\\Request;\nuse App\\Http\\Requests;\nuse App\\User;\n\nclass UserController extends Controller\n{\n\n    public function index(Request $request)\n    {\n        return User::filter($request-\u003eall())-\u003eget();\n    }\n\n}\n```\n\n## Configuration\n### Install Through Composer\n```\ncomposer require tucker-eric/eloquentfilter\n```\n\nThere are a few ways to define the filter a model will use:\n\n- [Use EloquentFilter's Default Settings](#default-settings)\n- [Use A Custom Namespace For All Filters](#with-configuration-file-optional)\n- [Define A Model's Default Filter](#define-the-default-model-filter-optional)\n- [Dynamically Select A Model's Filter](#dynamic-filters)\n\n\n#### Default Settings\nThe 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.\n\n|Model|ModelFilter|\n|-----|-----------|\n|`App\\User`|`App\\ModelFilters\\UserFilter`|\n|`App\\FrontEnd\\PrivatePost`|`App\\ModelFilters\\PrivatePostFilter`|\n|`App\\FrontEnd\\Public\\GuestPost`|`App\\ModelFilters\\GuestPostFilter`|\n\n#### Laravel\n\n##### With Configuration File (Optional)\n\n\u003e 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\n\nAfter installing the Eloquent Filter library, register the `EloquentFilter\\ServiceProvider::class` in your `config/app.php` configuration file:\n\n```php\n'providers' =\u003e [\n    // Other service providers...\n\n    EloquentFilter\\ServiceProvider::class,\n],\n```\n\nCopy the package config to your local config with the publish command:\n\n```bash\nphp artisan vendor:publish --provider=\"EloquentFilter\\ServiceProvider\"\n```\n\nIn the `config/eloquentfilter.php` config file.  Set the namespace your model filters will reside in:\n\n```php\n'namespace' =\u003e \"App\\\\ModelFilters\\\\\",\n```\n\n#### Lumen\n\n##### Register The Service Provider (Optional)\n\n\u003eThis is only required if you want to use the `php artisan model:filter` command.\n\nIn `bootstrap/app.php`:\n\n```php\n$app-\u003eregister(EloquentFilter\\LumenServiceProvider::class);\n```\n\n##### Change The Default Namespace\n\nIn `bootstrap/app.php`:\n\n```php\nconfig(['eloquentfilter.namespace' =\u003e \"App\\\\Models\\\\ModelFilters\\\\\"]);\n```\n\n#### Define The Default Model Filter (optional)\n\n\u003e The following is optional. If no `modelFilter` method is found on the model the model's filter class will be resolved by the [default naming conventions](#default-settings)\n\nCreate a public method `modelFilter()` that returns `$this-\u003eprovideFilter(Your\\Model\\Filter::class);` in your model.\n\n```php\n\u003c?php\n\nnamespace App;\n\nuse EloquentFilter\\Filterable;\nuse Illuminate\\Database\\Eloquent\\Model;\n\nclass User extends Model\n{\n    use Filterable;\n\n    public function modelFilter()\n    {\n        return $this-\u003eprovideFilter(\\App\\ModelFilters\\CustomFilters\\CustomUserFilter::class);\n    }\n\n    //User Class\n}\n```\n#### Dynamic Filters\n\nYou 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.\n\n```php\n\u003c?php\n\nnamespace App\\Http\\Controllers;\n\nuse Illuminate\\Http\\Request;\nuse App\\Http\\Requests;\nuse App\\User;\nuse App\\ModelFilters\\Admin\\UserFilter as AdminFilter;\nuse App\\ModelFilters\\User\\UserFilter as BasicUserFilter;\nuse Auth;\n\nclass UserController extends Controller\n{\n    public function index(Request $request)\n    {\n        $userFilter = Auth::user()-\u003eisAdmin() ? AdminFilter::class : BasicUserFilter::class;\n\n        return User::filter($request-\u003eall(), $userFilter)-\u003eget();\n    }\n}\n\n```\n\n### Generating The Filter\n\u003e Only available if you have registered `EloquentFilter\\ServiceProvider::class` in the providers array in your `config/app.php'\n\nYou can create a model filter with the following artisan command:\n\n```bash\nphp artisan model:filter User\n```\n\nWhere `User` is the Eloquent Model you are creating the filter for.  This will create `app/ModelFilters/UserFilter.php`\n\nThe 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:\n\n```bash\nphp artisan model:filter AdminFilters\\\\User\n```\n\nThis would create `app/ModelFilters/AdminFilters/UserFilter.php`\n\n## Usage\n\n### Defining The Filter Logic\nDefine the filter logic based on the camel cased input key passed to the `filter()` method.\n\n- Empty strings and null values are ignored by default.\n  - Empty strings and values can be configured not to be ignored by setting `protected $allowedEmptyFilters = false;` on a filter.\n- If a `setup()` method is defined it will be called once before any filter methods regardless of input\n- `_id` is dropped from the end of the input key to define the method so filtering `user_id` would use the `user()` method\n    - Can be changed with by definining `protected $drop_id = false;` on a filter\n- Input without a corresponding filter method are ignored\n- The value of the key is injected into the method\n- All values are accessible through the `$this-\u003einput()` method or a single value by key `$this-\u003einput($key)`\n- All Eloquent Builder methods are accessible in `$this` context in the model filter class.\n\nTo define methods for the following input:\n\n```php\n[\n    'company_id'   =\u003e 5,\n    'name'         =\u003e 'Tuck',\n    'mobile_phone' =\u003e '888555'\n]\n```\n\nYou would use the following methods:\n\n```php\n\nuse EloquentFilter\\ModelFilter;\n\nclass UserFilter extends ModelFilter\n{\n    protected $blacklist = ['secretMethod'];\n    \n    // This will filter 'company_id' OR 'company'\n    public function company($id)\n    {\n        return $this-\u003ewhere('company_id', $id);\n    }\n\n    public function name($name)\n    {\n        return $this-\u003ewhere(function($q) use ($name)\n        {\n            return $q-\u003ewhere('first_name', 'LIKE', \"%$name%\")\n                -\u003eorWhere('last_name', 'LIKE', \"%$name%\");\n        });\n    }\n\n    public function mobilePhone($phone)\n    {\n        return $this-\u003ewhere('mobile_phone', 'LIKE', \"$phone%\");\n    }\n\n    public function setup()\n    {\n        $this-\u003eonlyShowDeletedForAdmins();\n    }\n\n    public function onlyShowDeletedForAdmins()\n    {\n        if(Auth::user()-\u003eisAdmin())\n        {\n            $this-\u003ewithTrashed();\n        }\n    }\n    \n    public function secretMethod($secretParameter)\n    {\n        return $this-\u003ewhere('some_column', true);\n    }\n}\n```\n\n\u003e **Note:**  In the above example if you do not want `_id` dropped from the end of the input you can set `protected $drop_id = false` on your filter class.  Doing this would allow you to have a `company()` filter method as well as a `companyId()` filter method.\n\n\n\u003e **Note:**  In the above example if you do not want `mobile_phone` to be mapped to `mobilePhone()` you can set `protected $camel_cased_methods = false` on your filter class. Doing this would allow you to have a `mobile_phone()` filter method instead of `mobilePhone()`. By default, `mobilePhone()` filter method can be called thanks to one of the following input key: `mobile_phone`, `mobilePhone`, `mobile_phone_id`\n\n\u003e **Note:** In the example above all methods inside `setup()` will be called every time `filter()` is called on the model\n\n#### Blacklist\n\nAny methods defined in the `blackist` array will not be called by the filter. Those methods are normally used for internal filter logic.\n\nThe `blacklistMethod()` and `whitelistMethod()` methods can be used to dynamically blacklist and whitelist methods.\n\nIn 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:\n\nExample:\n```php\npublic function setup()\n{\n    if(Auth::user()-\u003eisAdmin()) {\n        $this-\u003ewhitelistMethod('secretMethod');\n    }\n}\n```\n\n\n#### Additional Filter Methods\n\nThe `Filterable` trait also comes with the below query builder helper methods:\n\n|EloquentFilter Method|QueryBuilder Equivalent|\n|---|---|\n|`$this-\u003ewhereLike($column, $string)`|`$query-\u003ewhere($column, 'LIKE', '%'.$string.'%')`|\n|`$this-\u003ewhereLike($column, $string, 'or')`|`$query-\u003eorWhere($column, 'LIKE', '%'.$string.'%')`|\n|`$this-\u003ewhereBeginsWith($column, $string)`|`$query-\u003ewhere($column, 'LIKE', $string.'%')`|\n|`$this-\u003ewhereBeginsWith($column, $string, 'or')`|`$query-\u003eorWhere($column, 'LIKE', $string.'%')`|\n|`$this-\u003ewhereEndsWith($column, $string)`|`$query-\u003ewhere($column, 'LIKE', '%'.$string)`|\n|`$this-\u003ewhereEndsWith($column, $string, 'or')`|`$query-\u003eorWhere($column, 'LIKE', '%'.$string)`|\n\nSince 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.\n\n\n### Applying The Filter To A Model\n\nImplement the `EloquentFilter\\Filterable` trait on any Eloquent model:\n\n```php\n\u003c?php\n\nnamespace App;\n\nuse EloquentFilter\\Filterable;\nuse Illuminate\\Database\\Eloquent\\Model;\n\nclass User extends Model\n{\n    use Filterable;\n\n    //User Class\n}\n```\n\nThis gives you access to the `filter()` method that accepts an array of input:\n\n```php\nclass UserController extends Controller\n{\n    public function index(Request $request)\n    {\n        return User::filter($request-\u003eall())-\u003eget();\n    }\n}\n```\n\n## Filtering By Relationships\n\u003eThere are two ways to filter by related models.  Using the `$relations` array 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 the `related()` 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 `$relations` array you want to use that Model's filter for as well as use the `related()` method to define local methods on that same relation.  Both methods nest the filter constraints into the same `whereHas()` query on that relation.\n\nFor both examples we will use the following models:\n\nA `App\\User` that `hasMany` `App\\Client::class`:\n\n```php\nclass User extends Model\n{\n    use Filterable;\n\n    public function clients()\n    {\n        return $this-\u003ehasMany(Client::class);\n    }\n}\n```\n\nAnd each `App\\Client` belongs to `App\\Industry::class`:\n\n```php\nclass Client extends Model\n{\n    use Filterable;\n\n    public function industry()\n    {\n        return $this-\u003ebelongsTo(Industry::class);\n    }\n    \n    public function scopeHasRevenue($query)\n    {\n        return $query-\u003ewhere('total_revenue', '\u003e', 0);\n    }\n}\n```\n\n\nWe want to query our users and filter them by the industry and volume potential of their clients that have done revenue in the past.\n\nInput used to filter:\n\n```php\n$input = [\n    'industry'         =\u003e '5',\n    'potential_volume' =\u003e '10000'\n];\n```\n\n### Setup\n\nBoth 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:\n\n```php\nclass UserFilter extends ModelFilter\n{\n    public function clientsSetup($query)\n    {\n        return $query-\u003ehasRevenue();\n    }\n}\n```\nThis 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.\n\n\u003e You can learn more about scopes [here](https://laravel.com/docs/master/eloquent#local-scopes)\n\n\n### Ways To Filter Related Models \n\n- [With The `related()` Method](#filter-related-models-with-the-related-method)\n- [Using The `$relations` Array](#filter-related-models-using-the-relations-array)\n- [With Both Methods](#filter-related-models-with-both-methods)\n\n#### Filter Related Models With The `related()` Method:\n\nThe `related()` method is a little easier to setup and is great if you aren't going to be using the related Model's filter to ever filter that Model explicitly.  The `related()` method takes the same parameters as the `Eloquent\\Builder`'s `where()` method except for the first parameter being the relationship name.\n\n##### Example:\n\n\n`UserFilter` with an `industry()` method that uses the `ModelFilter`'s `related()` method\n\n```php\nclass UserFilter extends ModelFilter\n{\n    public function industry($id)\n    {\n        return $this-\u003erelated('clients', 'industry_id', '=', $id);\n        \n        // This would also be shorthand for the same query\n        // return $this-\u003erelated('clients', 'industry_id', $id);\n    }\n    \n    public function potentialVolume($volume)\n    {\n        return $this-\u003erelated('clients', 'potential_volume', '\u003e=', $volume);\n    }\n}\n```\n\nOr you can even pass a closure as the second argument which will inject an instance of the related model's query builder like:\n\n```php\n    $this-\u003erelated('clients', function($query) use ($id) {\n        return $query-\u003ewhere('industry_id', $id);\n    });\n```\n\n#### Filter Related Models Using The `$relations` Array:\n\nAdd the relation in the `$relations` array with the name of the relation as referred to on the model as the key and an array of input keys that was passed to the `filter()` method.\n\nThe related model **MUST** have a ModelFilter associated with it.  We instantiate the related model's filter and use the input values from the `$relations` array to call the associated methods.\n\nThis is helpful when querying multiple columns on a relation's table while avoiding multiple `whereHas()` calls for the same relationship.  For a single column using a `$this-\u003ewhereHas()` method in the model filter works just fine.  In fact, under ther hood the model filter applies all constraints in the `whereHas()` method.\n\n##### Example:\n\n`UserFilter` with the relation defined so it's able to be queried.\n\n```php\nclass UserFilter extends ModelFilter\n{\n    public $relations = [\n        'clients' =\u003e ['industry', 'potential_volume'],\n    ];\n}\n```\n\n`ClientFilter` with the `industry` method that's used to filter:\n\u003e **Note:** The `$relations` array should identify the relation and the input key to filter by that relation. Just as the `ModelFilter` works, this will access the camelCased method on that relation's filter. If the above example was using the key `industry_type` for the input the relations array would be `$relations = ['clients' =\u003e ['industry_type']]` and the `ClientFilter` would have the method `industryType()`.\n\n```php\nclass ClientFilter extends ModelFilter\n{\n    public $relations = [];\n\n    public function industry($id)\n    {\n        return $this-\u003ewhere('industry_id', $id);\n    }\n    \n    public function potentialVolume($volume)\n    {\n        return $this-\u003ewhere('potential_volume', '\u003e=', $volume);\n    }\n}\n```\n##### `$relations` array alias support\nThe `$relations` array supports aliases. This is used when the input doesn't match the related model's filter method.\nThis will transform the input keys being passed to the related model filter's input.\n\n##### Example:\n```php\nclass UserFilter extends ModelFilter\n{\n    public $relations = [\n        'clients' =\u003e [\n            'client_industry'  =\u003e 'industry',\n            'client_potential' =\u003e 'potential_volume'\n        ]\n    ];\n}\n```\n\nThe above will receive an array like:\n```php\n[\n    'client_industry'  =\u003e 1,\n    'client_potential' =\u003e 100000\n]\n```\nAnd the `ClientFilter` will receive it as:\n```php\n[\n    'industry'         =\u003e 1,\n    'potential_volume' =\u003e 100000\n]\n```\nAllowing for more descriptive input names without filters needing to match. Allowing for more reuse of the same filters.\n\n#### Filter Related Models With Both Methods\nYou can even use both together and it will produce the same result and only query the related model once.  An example would be:\n\nIf the following array is passed to the `filter()` method:\n\n```php\n[\n    'name'             =\u003e 'er',\n    'last_name'        =\u003e '',\n    'company_id'       =\u003e 2,\n    'roles'            =\u003e [1,4,7],\n    'industry'         =\u003e 5,\n    'potential_volume' =\u003e '10000'\n]\n```\n\nIn `app/ModelFilters/UserFilter.php`:\n\n```php\n\u003c?php namespace App\\ModelFilters;\n\nuse EloquentFilter\\ModelFilter;\n\nclass UserFilter extends ModelFilter\n{\n    public $relations = [\n        'clients' =\u003e ['industry'],\n    ];\n    \n    public function clientsSetup($query)\n    {\n        return $query-\u003ehasRevenue();\n    }\n\n    public function name($name)\n    {\n        return $this-\u003ewhere(function($q)\n        {\n            return $q-\u003ewhere('first_name', 'LIKE', $name . '%')-\u003eorWhere('last_name', 'LIKE', '%' . $name.'%');\n        });\n    }\n    \n    public function potentialVolume($volume)\n    {\n        return $this-\u003erelated('clients', 'potential_volume', '\u003e=', $volume);\n    }\n\n    public function lastName($lastName)\n    {\n        return $this-\u003ewhere('last_name', 'LIKE', '%' . $lastName);\n    }\n\n    public function company($id)\n    {\n        return $this-\u003ewhere('company_id',$id);\n    }\n\n    public function roles($ids)\n    {\n        return $this-\u003ewhereHas('roles', function($query) use ($ids)\n        {\n            return $query-\u003ewhereIn('id', $ids);\n        });\n    }\n}\n```\n\n##### Adding Relation Values To Filter\n\nSometimes, based on the value of a parameter you may need to push data to a relation filter.  The `push()` method does just this.\nIt accepts one argument as an array of key value pairs or two arguments as a key value pair `push($key, $value)`.\nRelated models are filtered AFTER all local values have been executed you can use this method in any filter method.\nThis avoids having to query a related table more than once.  For Example:\n\n```php\npublic $relations = [\n    'clients' =\u003e ['industry', 'status'],\n];\n\npublic function statusType($type)\n{\n    if($type === 'all') {\n        $this-\u003epush('status', 'all');\n    }\n}\n```\n\nThe above example will pass `'all'` to the `status()` method on the `clients` relation of the model.\n\u003e Calling the `push()` method in the `setup()` method will allow you to push values to the input for filter it's called on\n\n#### Pagination\n\nIf you want to paginate your query and keep the url query string without having to use:\n\n```php\n{!! $pages-\u003eappends(Input::except('page'))-\u003erender() !!}\n```\n\nThe `paginateFilter()` and `simplePaginateFilter()` methods accept the same input as [Laravel's paginator](https://laravel.com/docs/master/pagination#basic-usage) and returns the respective paginator.\n\n```php\nclass UserController extends Controller\n{\n    public function index(Request $request)\n    {\n        $users = User::filter($request-\u003eall())-\u003epaginateFilter();\n\n        return view('users.index', compact('users'));\n    }\n```\n\nOR:\n\n```php\n    public function simpleIndex(Request $request)\n    {\n        $users = User::filter($request-\u003eall())-\u003esimplePaginateFilter();\n\n        return view('users.index', compact('users'));\n    }\n}\n```\n\nIn your view `$users-\u003erender()` will return pagination links as it normally would but with the original query string with empty input ignored if `protected $allowedEmptyFilters` is not set to `false` on the filter.\n\n\n# Contributing\nAny contributions are welcome!\n","funding_links":[],"categories":["数据库( Database )"],"sub_categories":[],"project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Ftucker-eric%2Feloquentfilter","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Ftucker-eric%2Feloquentfilter","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Ftucker-eric%2Feloquentfilter/lists"}