{"id":22147542,"url":"https://github.com/myerscode/laravel-query-strategies","last_synced_at":"2025-07-26T02:31:54.421Z","repository":{"id":57022619,"uuid":"147007154","full_name":"myerscode/laravel-query-strategies","owner":"myerscode","description":"A package for applying filters, ordering, eager loads, result limiting and pagination to Eloquent queries","archived":false,"fork":false,"pushed_at":"2023-05-12T15:03:54.000Z","size":86,"stargazers_count":4,"open_issues_count":0,"forks_count":0,"subscribers_count":2,"default_branch":"master","last_synced_at":"2024-11-21T07:47:22.362Z","etag":null,"topics":["eloquent","filter","laravel","laravel-query-strategies","ordering","pagination","query"],"latest_commit_sha":null,"homepage":"","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/myerscode.png","metadata":{"files":{"readme":"README.md","changelog":"CHANGES.md","contributing":null,"funding":null,"license":"LICENSE","code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null}},"created_at":"2018-09-01T14:53:05.000Z","updated_at":"2023-05-12T15:01:46.000Z","dependencies_parsed_at":"2022-08-23T12:20:34.803Z","dependency_job_id":null,"html_url":"https://github.com/myerscode/laravel-query-strategies","commit_stats":null,"previous_names":[],"tags_count":6,"template":false,"template_full_name":null,"repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/myerscode%2Flaravel-query-strategies","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/myerscode%2Flaravel-query-strategies/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/myerscode%2Flaravel-query-strategies/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/myerscode%2Flaravel-query-strategies/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/myerscode","download_url":"https://codeload.github.com/myerscode/laravel-query-strategies/tar.gz/refs/heads/master","host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":227642172,"owners_count":17797850,"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":["eloquent","filter","laravel","laravel-query-strategies","ordering","pagination","query"],"created_at":"2024-12-01T23:18:19.089Z","updated_at":"2024-12-01T23:18:19.880Z","avatar_url":"https://github.com/myerscode.png","language":"PHP","funding_links":[],"categories":[],"sub_categories":[],"readme":"# Laravel Query Strategies\na package to help build queries with Eloquent Builder from URL parameters in a request\n\n[![Latest Stable Version](https://poser.pugx.org/myerscode/laravel-query-strategies/v/stable)](https://packagist.org/packages/myerscode/laravel-query-strategies)\n[![Total Downloads](https://poser.pugx.org/myerscode/laravel-query-strategies/downloads)](https://packagist.org/packages/myerscode/laravel-query-strategies)\n[![License](https://poser.pugx.org/myerscode/laravel-query-strategies/license)](https://packagist.org/packages/myerscode/laravel-query-strategies)\n\n## Why this package is helpful?\nIf you want to apply query clauses to Eloquent Models using parameters passed by the user, then this package will  allow you to create strategies that will enable them to be applied automatically.\n\nUsing query strategies you can define what properties a user can have access to offering a safer way for them interact with your data schemas. \n\nStrategies can obfuscate the real column names, add aliases to them and enable/disable the query clauses that can be applied to the model.\n\nYou can work the builder before and after applying a strategy, so it can be easily integrated with existing code and queries.\n\n## Installation\n\nYou can install the package via composer:\n\n```bash\ncomposer require myerscode/laravel-query-strategies\n```\n\n## Applying strategies\n\nGetting a filter instance by using one of the following methods:\n\n\nUsing the global helper\n```php\nfilter(Item::class)-\u003ewith(MyStrategy::class);\n```\n\nUse the facade\n```php\nQuery::filter(Item::class)-\u003ewith(MyStrategy::class);\n```\n\nBuilding it yourself\n```php\nnew Filter(Item::query(), new MyStrategy, $request-\u003equery-\u003eall());\n```\n\nUsing the `IsFilterable` trait\n\n```php\nclass Foo extends Model\n{\n    use IsFilterableTrait;\n\n    public $strategy = BarStrategy::class;\n}\n\n```\nYou can then use the model itself to apply the filter\n\n```php\n$filter = (new Foo)-\u003efilter();\n```\n\nYou can apply query filters, ordering, limits, includes, pagination.\n\n```php\n$filter-\u003eapply(); // Applies filter, order, limit, with methods and returns the paginated query\n$filter-\u003efilter(); // Only applies filters and returns the Filter class\n$filter-\u003eorder(); // Only applies ordering and returns the Filter class\n$filter-\u003elimit(); // Only applies limiting and returns the Filter class\n$filter-\u003ewith(); // Only applies includes and returns the Filter class\n$filter-\u003epaginate(); // Applies pagination and returns a LengthAwarePaginator class\n$filter-\u003ebuilder(); // Return the builder\n```\n\n## Strategies\n\nWith strategies you can:\n* Have a set disable \"default\" clauses parameters can use\n* Set what query clauses a parameter can do\n    * You can create custom clauses\n    * Disable clauses from a parameter\n    * Set default clauses the parameter uses\n* Add aliases to your columns\n* Alias clauses to allow better for API experiences\n* Automatically apply `with` the builder can eager load\n* Set query limiting which can be capped to prevent service degradation\n* Set columns the query can be ordered by\n* Paginate the results\n\n## Strategy structure\n\n### $config\n\nFill in the `$config` property with the query parameters that you want use on the model.\n\n`$config` should contain the allowed queries keys and the values `aliases` `column` `default` `disabled` `methods`\n\n```php\n// basic implamentation, that will just enable all default clauses for the strategy and will not mask the column name\n$config = [\n  'foo',\n  'bar'  \n];\n```\n\n```php\n// advance with custom methods, disabling clauses and changing the default clause\n$config = [\n    'name' =\u003e [\n        'column' =\u003e 'first_name',\n        'methods' =\u003e [\n            'hello' =\u003e HelloClause::class,\n            'world' =\u003e WorldClause::class,\n        ]\n    ],\n    'surname' =\u003e [\n        'column' =\u003e 'last_name',\n        'disabled' =\u003e [\n            'equals' =\u003e EqualsClause::class,\n        ],\n    ],\n    'dob' =\u003e [\n        'aliases' =\u003e [\n            'date_of_birth',\n            'birthday',\n        ]\n        'default' =\u003e FooBarClause::class,\n    ],\n    'address' =\u003e [\n        'methods' =\u003e [\n            'distance' =\u003e DistanceClause::class,\n        ],\n    ],\n];\n```\n\n### $defaultMethods\nThe `$defaultMethods` property contains all the clauses against an collection of `aliases` that properties can use. \n\nOverriding this property will enable you to control what default methods a query can apply to a property of `Model`.\n\n```php\nprotected $defaultMethods = [\n    ...\n    LessThanClause::class =\u003e ['lessThan', '\u003c', 'lt'],\n    GreaterThanOrEqualsClause::class =\u003e ['greaterThanOrEquals', '\u003e=', 'gte'],\n    ...\n];\n```\n\n### $limitTo\nThe `$limitTo` property sets what the default select limit is by default.\n\n```php\n// default value\nprotected $limitTo = 50;\n```\n\n### $maxLimit\nThe `$maxLimit` property sets what the max limit is, to help prevent people selecting all records form you database and degrading performance.\n\n```php\n// default value\nprotected $maxLimit = 150;\n```\n\n### $orderBy\nThe `$orderBy` property is an array which sets what columns the `Model` can be ordered by.\n\n```php\n// default value\nprotected $canOrderBy = [\n    'id',\n];\n```\n\n## Filters\n\nBy default parameters will have access to all the query filters in the `$defaultMethods`. \nYou can create custom a `Clause` to do more complex or domain specific actions and add them to `$defaultMethods` or a single parameter.\n\n### Where Clauses\n\n| Type          | Aliases   | Query   | Eloquent   |\n| ------------- |---------- | ------- | ---------- |\n| begins with | `beginsWith` `*%` | `?name[beginsWith]=Fr` `?name[*%]=Fr` | Record::where('name', '=', 'Fr%') |\n| contains | `contains` `%%` | `?name[contains]=Fr` `?name[%%]=Fr` | Record::where('name', '=', '%Fr%') |\n| ends with | `endsWith` `%*` | `?name[endsWith]=ed` `?name[%*]=ed` | Record::where('name', '=', '%ed') |\n| equals | `is` `=` | `?name=Fred` `?name[is]=Fred` `?name[is]=Fred` | Record::where('name', '=', 'Fred') |\n| less than | `lessThan` `\u003c` `lt` | `?hello[lessThan]=world` `?hello[\u003c]=world` `?hello[lt]=world` | Record::where('hello', '\u003c', 'world') |\n| less than or equals | `lessThanOrEquals` `\u003c=` `lte` | `?hello[lessThanOrEquals]=world` `?hello[\u003c=]=world` `?hello[lte]=world` | Record::where('hello', '\u003c=', 'world') |\n| greater than | `greaterThan` `\u003e` `gt` | `?hello[greaterThan]=world` `?hello[\u003e]=world` `?hello[gt]=world` | Record::where('hello', '\u003e', 'world') |\n| greater than or equals | `greaterThanOrEquals` `\u003e=` `gte` | `?hello[greaterThanOrEquals]=world` `?hello[\u003e=]=world` `?hello[gte]=world` | Record::where('hello', '\u003e=', 'world') |\n| not equals | `not` `!` | `?name[not]=Fred` `?name[!]=Fred` | Record::where('hello', '!=', 'world') |\n| is in | `isIn` `in` | `?name[isIn]=Fred,Tor` `?name[in]=Fred,Tor` `?name[]=Fred\u0026name[]=Tor` | Record::whereIn('name', ['Fred', 'Tor']) |\n| is not in | `notIn` `!in` | `?name[notIn]=Fred,Tor` `?name[!in]=Fred,Tor`  | Record::whereNotIn('name', ['Fred', 'Tor']) |\n| or | `or` \u003ccode\u003e\u0026#124;\u0026#124;\u003c/code\u003e  | `?name[is]=Fred\u0026name[or]=Tor` | Record::where('name', '=', 'Fred')-\u003eorWhere('name', '=', 'Tor') |\n\n### Overriding the clause\n\nYou can use a special parameter to set a clause to all properties with that name in a query.\n\nThe following example would apply the `not` clause to the `name` properties.\n\n```php\n?name[]=Fred\u0026name[]=Tor\u0026name[]=Chris\u0026name--operator=not\n```\n\nBy default the special parameter is `$paramName` with a default suffix of `--operator`. e.g. `name--operator`\n\nThe parameter can be either fully renamed or the suffix changed in the strategy config.\n\n```php\n// a strategy config with operator override properties\n$config = [\n    'name' =\u003e [\n        'override' =\u003e 'name_override',\n    ],\n    'date' =\u003e [\n        'overrideSuffix' =\u003e '--filter',\n    ],\n];\n// name=Fred\u0026name_override=like\n// date=31/12/1987\u0026date--filter=before\n```\n\n### Properties with multiple values\n\nIf a property passed is found to be an array e.g. `name[]=Fred\u0026name[]=Tor\u0026name[]=Chris` then by default the `IsInClause` is used.\n\nA property can be set to explode its values on a delimiter, so multiple values can be passed at once to a single parameter e.g. `name=Fred,Tor,Chris`.\nBy default this is disabled and will need to be set on a property-by-property basis and is enabled by setting `explode` to true in the property config. \nThe delimiter can be changed from the default `,` character using the `delimiter` config option.\n\n```php\n// a strategy config with operator override properties\n$config = [\n    'name' =\u003e [\n        'explode' =\u003e true,\n    ],\n    'date' =\u003e [\n        'explode' =\u003e true,\n        'delimiter' =\u003e '||',\n    ],\n];\n// name=Fred,Tor\n// date=31/12/1987||12/07/1989\n```\n\n### Properties with clause in name\n\nA property can be passed with its clause appended in the field name with `--` as a separator.\n\n`?name--contains=ed`\n\n### Ordering and Sorting\nSorting is ascending by default. The only available options for sorting is `asc` and `desc` - if a value other than those is past, it will resort to the default.\n`?order=name\u0026sort=desc`\n\n`?order[asc]=name\u0026order[desc]=id`\n\n### Limiting\n\n`?limit=10`\n\n`?order[asc]=name\u0026order[desc]=id`\n\n### Using the config\nRun the publish command, to create the config file in `/config`\n```\n\u003e php artisan vendor:publish --provider=\"Myerscode\\Laravel\\QueryStrategies\\ServiceProvider\" --tag=config\n```\nThis will create `config/query-strategies.php` which contains the default settings for things such as reserved parameter keys (limit, page, with etc.)\n\n\n## Creating a new strategy\nTo quickly create a new `Strategy` class in `Queries/Strategies` run:\n```\n\u003e php artisan make:strategy $name\n```\n\n\n## Creating a new query clause\nTo quickly create a new `Clause` class in `Queries/Clause` run:\n```\n\u003e php artisan make:clause $name\n```\n\n## License\n\nThe MIT License (MIT). Please see [License File](LICENSE) for more information.\n","project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fmyerscode%2Flaravel-query-strategies","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Fmyerscode%2Flaravel-query-strategies","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fmyerscode%2Flaravel-query-strategies/lists"}