John Davidson

php - Format result for requesting all data

0 comments
Message:


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
];
}


My Answer:
public function index()
{
$tests = Test::all();
return \App\Http\Resources\TestRessource::collection($tests);
}

Rate this post

5 of 5 based on 3758 votes

Comments




© 2024 Hayatsk.info - Personal Blogs Platform. All Rights Reserved.
Create blog  |  Privacy Policy  |  Terms & Conditions  |  Contact Us