Laravel8 API资源(resource)响应格式添加 c
2021-09-01 本文已影响0人
囧囧的猪
我们在给前端提供API的时候,不仅要提供data数据,往往还需要提供自定义状态码(code)与对应信息(msg)laravel8提供了API资源添加顶级元数据的方法。
API资源(resource) 添加顶级元数据code与msg
- 生成HomeController对应的API资源
php artisan make:resource HomeResource
- 生成的HomeResource.php如下:
<?php
namespace App\Http\Resources;
use Illuminate\Http\Resources\Json\JsonResource;
class HomeResource extends JsonResource
{
/**
* Transform the resource into an array.
*
* @param \Illuminate\Http\Request $request
* @return array
*/
public function toArray($request)
{
return parent::toArray($request);
}
}
- 在HomeController中使用:调用additional方法添加顶级元数据
<?php
namespace App\Http\Controllers;
use App\Http\Resources\HomeResource;
use App\Models\HomeModel;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;
class HomeController
{
public function index()
{
// 单条(find())数据使用make方法
return HomeResource::make(HomeModel::find(1))->additional(['code' => 1, 'msg' => 'API调用成功']);
// 多条数据 all()、get()或分页(paginate)使用collection方法
return HomeResource::collection(HomeModel::all())->additional(['code' => 1, 'msg' => 'API调用成功']);
}
}
- find()响应体
{
"code": 1,
"msg": "API调用成功",
"data": {
"id": 1,
"name": "home",
"created_at": "2021-09-02 01:04:12",
"updated_at": "2021-09-02 01:04:12"
}
}
- 多条数据响应体
{
"code": 1,
"msg": "API调用成功",
"data": [
{
"id": 1,
"name": "home",
"created_at": "2021-09-02 01:04:12",
"updated_at": "2021-09-02 01:04:12"
},
{
"id": 2,
"name": "home2",
"created_at": "2021-09-02 01:04:12",
"updated_at": "2021-09-02 01:04:12"
},
{
"id": 3,
"name": "home3",
"created_at": "2021-09-02 01:04:12",
"updated_at": "2021-09-02 01:04:12"
}
],
"links": {
"first": "http://localhost:8092/api/home?page=1",
"last": "http://localhost:8092/api/home?page=1",
"prev": null,
"next": null
},
"meta": {
"current_page": 1,
"from": 1,
"last_page": 1,
"links": [
{
"url": null,
"label": "« Previous",
"active": false
},
{
"url": "http://localhost:8092/api/home?page=1",
"label": "1",
"active": true
},
{
"url": null,
"label": "Next »",
"active": false
}
],
"path": "http://localhost:8092/api/home",
"per_page": 10,
"to": 3,
"total": 3
}
}
希望能对您有所帮助