【发布时间】:2022-01-20 11:46:49
【问题描述】:
我的控制器带有index() 和show()。
{
/**
* Display a listing of the resource.
*
* @return \App\Http\Resources\MyRessource
*/
public function index()
{
//???
}
/**
* Display the specified resource.
*
* @param \App\Models\Test $test
* @return \App\Http\Resources\TestRessource
*/
public function show(Test $test)
{
return new \App\Http\Resources\TestRessource($test);
}
}
在我的资源中,show() 具有我想要返回的格式,因此http://127.0.0.1/Test/1 的结果是带有格式化 JSON 的 ID 1。
{
"data": {
"id": 1,
"ref": "0103573026466442101007175850",
"tax": null,
"date_in": "2021-10-08T12:37:05.000000Z",
"date_out": "2021-10-11T08:02:17.000000Z"
}
}
我希望index() 使用我的资源以相同的方式返回。
当我在 http://127.0.0.1/Test 上执行 index() 时,它会返回我的所有数据,但不是我想要的格式化 JSON。
资源代码:
{
/**
* Transform the resource into an array.
*
* @param \Illuminate\Http\Request $request
* @return array|\Illuminate\Contracts\Support\Arrayable|\JsonSerializable
*/
public function toArray($request)
{
return [
"id" => $this->id,
"ref" => $this->ref,
"tax" => $this->tax,
"date_in" => $this->date_in,
"date_out" => $this->date_out
];
}
【问题讨论】:
标签: php laravel-8 laravel-eloquent-resource