myerscode/laravel-query-strategies
Composer 安装命令:
composer require myerscode/laravel-query-strategies
包简介
A package for applying filters, ordering, eager loads, result limiting and pagination to Eloquent queries
README 文档
README
Build safe, flexible API endpoints by turning URL query parameters into Eloquent queries. Define a strategy that controls exactly which filters, sorts, fields, and relationships your API consumers can use.
Requirements
- PHP ^8.5
- Laravel ^13.0
Quick Example
Given a ProductStrategy that defines which parameters are allowed:
class ProductStrategy extends Strategy { protected array $canOrderBy = ['name', 'price', 'created_at']; protected array $canWith = ['category', 'reviews']; protected array $allowedFields = ['id', 'name', 'price', 'category_id']; protected array $allowedAppends = ['discount_price']; protected array $config = [ 'name' => ['filter' => ContainsClause::class], 'price' => ['column' => 'unit_price'], 'category' => ['column' => 'category_id', 'explode' => true], ]; }
Your API consumers can now query like this:
GET /products?name=laptop&price=500&category=1,2,3&order=price&sort=desc&limit=10&with=reviews&fields=id,name,price&append=discount_price
And in your controller:
use function Myerscode\Laravel\QueryStrategies\filter; public function index() { return filter(Product::class)->with(ProductStrategy::class)->apply(); }
That single line handles filtering, sorting, field selection, eager loading, accessor appending, limiting, and pagination — all controlled by the strategy.
Why Use This?
- Safe by default — only parameters defined in your strategy are applied. Unknown parameters are ignored (or rejected in strict mode).
- Column obfuscation — map public parameter names to real database columns so your schema stays private.
- Flexible clauses — 17 built-in filter clauses (equals, contains, between, greater than, etc.) with operator overrides via URL.
- Relationship support — filter through relationships with dot notation, sort by relationship columns, and control eager loading.
- Composable — chain individual methods (
filter(),order(),fields(), etc.) or callapply()to run everything at once.
Installation
composer require myerscode/laravel-query-strategies
The package auto-discovers its service provider. No manual registration needed.
Documentation
- Usage — Getting started, creating filters, query parameter syntax, and pagination
- Strategies — Defining strategies, parameter options, ordering, limiting, eager loads, and default filters
- Clauses — Built-in clauses, scope and trashed filtering, callbacks, and custom clauses
- Transmutes — Transforming values before filtering
- Configuration — Customising parameter names and strict mode
License
The MIT License (MIT). Please see License File for more information.
统计信息
- 总下载量: 62
- 月度下载量: 0
- 日度下载量: 0
- 收藏数: 4
- 点击次数: 2
- 依赖项目数: 0
- 推荐数: 0
其他信息
- 授权协议: MIT
- 更新时间: 2018-09-01