Mar 19, 2022
0
Level 1
API Resource with & returning columns
Two part question, the below code is a API Resource which returns transformed data from API.
I have included a "with" function, but the response doesn't include the "with" it doesn't work?
Secondly, is there a better way of including the current resource columns, as the frontend requires it.
Currently, I just return a columns array with the correct columns using "with" but the "with" doesns't work.
<?php
namespace App\Http\Resources;
use Illuminate\Http\Resources\Json\JsonResource;
class PrescriptionResource extends JsonResource
{
/**
* 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,
'prescription' => $this->name,
'quantity' => $this->quantity,
'cost' => $this->cost,
'repeat' => $this->repeat,
'company_id' => $this->company->id,
'company' => $this->company->name,
'location_id' => $this->location->id,
'location' => $this->location->name,
'manufacturer_id' => $this->manufacturer->id,
'manufacturer' => $this->manufacturer->name,
'practice_id' => $this->practice->id,
'practice' => $this->practice->name,
'prescriber_id' => $this->prescriber->id,
'prescriber' => $this->prescriber->name,
'created_at' => $this->created_at,
'updated_at' => $this->updated_at,
];
}
/**
* Get additional data that should be returned with the resource array.
*
* @param \Illuminate\Http\Request $request
* @return array
*/
public function with($request)
{
return [
'columns' => [
'id',
'prescription',
'quantity',
'cost',
'repeat',
'company_id',
'company',
'location_id',
'location',
'manufacturer_id',
'manufacturer',
'practice_id',
'practice',
'prescriber_id',
'prescriber',
'created_at',
'updated_at',
],
];
}
}
/**
* Display a listing of the resource.
*
*/
public function index()
{
$prescriptions = Prescription::paginate(5);
return PrescriptionResource::collection($prescriptions);
}
{
"data": [],
"links": {},
"meta": {
"current_page": 1,
"from": 1,
"last_page": 181,
"links": [],
"path": "https://.io/project/public/prescriptions",
"per_page": 5,
"to": 5,
"total": 904
}
}
No "columns" array included with "with" functin.
Please or to participate in this conversation.