mannysoft / hanap
该包最新版本(dev-master)没有可用的许可信息。
laravel 包 API 结果过滤、排序与搜索。
dev-master
2018-09-13 15:11 UTC
Requires
- php: >=7.0.0
- sofa/eloquence: 5.6.*
This package is not auto-updated.
Last update: 2024-09-15 04:26:13 UTC
README
laravel 包 API 结果过滤、排序与搜索。
安装
使用 composer 安装此包。
composer require mannysoft/hanap
Laravel 5.5 使用包自动发现,因此不需要您手动添加 ServiceProvider。
使用方法
namespace App\Models; use Illuminate\Database\Eloquent\Model; use Mannysoft\Hanap\FilterTrait; use Mannysoft\Hanap\FilterScope; class Team extends Model { use FilterTrait; protected $fillable = ['name']; protected $filters = ['status']; // field to filter ?status=active protected $sorts = ['name', 'status']; // fields to ?sort=name ?sort=-name ?sort=name,-status protected $searchableColumns = ['name']; // fields to search /** * The "booting" method of the model. * * @return void */ protected static function boot() { parent::boot(); static::addGlobalScope(new FilterScope); } }
现在您可以在模型中使用它。
// Will automatically run the filters, sorts and search $teams = Team::all();
GET /teams?status=active // Get active teams GET /teams?sort=-name,created_at // Retrieves a list of teams in descending order of name. Within a specific name, older teams are ordered first GET /teams?q=manny // Retrieves data mentioning the word 'manny' GET /teams?fields=id,name // Retrieves fields 'id' and 'name'
namespace App\Http\Resources; use Illuminate\Http\Resources\Json\Resource; class TeamResource extends Resource { /** * Transform the resource into an array. * * @param \Illuminate\Http\Request $request * @return array */ public function toArray($request) { return show_fields([ 'id' => $this->id, 'name' => $this->name, 'created_at' => $this->created_at, 'updated_at' => $this->updated_at, ]); } }
{ "data": [ { "id": 1, "name": "Dream Team" }, { "id": 2, "name": "Team 1" } ] }