I have my controller with index()
and 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);
}
}
In my resource the show()
has the format I want for return, so the result for http://127.0.0.1/Test/1 is the ID 1 with the formatted JSON.
{
"data": {
"id": 1,
"ref": "0103573026466442101007175850",
"tax": null,
"date_in": "2021-10-08T12:37:05.000000Z",
"date_out": "2021-10-11T08:02:17.000000Z"
}
}
I want the index()
to return the same way by using my resource.
When I do index()
on http://127.0.0.1/Test, it returns all my data but not in the formatted JSON that I want.
Resource code:
{
/**
* 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
];
}
On index()
do as in docs.
return TestRessource::collection(Test::all());