how can I reformat data from the database easily with relationships in Laravel, have been looping through the queried data and reformat as I loop then push in an array then after I return the array as a json but I’m finding challenges as the data grows it is totally slowing down.Is there a better way to do it.
>Solution :
Oh, I also have that problem but the better way to solve it is to use laravel Eloquent API Resources for example to create a resource using this command.
php artisan make:resource UserResource
Then after you can reformat your data and relationships from that resource for example like below
public function toArray($request)
{
// return parent::toArray($request);
return [
'id' => $this->id,
'patientName' => $this->patient_name,
'patientContact' => $this->patient_contact,
'patientEmail' => $this->patient_email,
'patientCode' => $this->patient_code,
'NIN' => $this->patient_nin,
'country' => $this->country,
'DOB' => $this->dateofbirth,
'patientAddress' => $this->patient_address,
'branch' => $this->whenLoaded('branch'),
'gender' => $this->gender,
'country_details' => $this->whenLoaded('cou'),
'status' => $this->p_status,
'visits' => $this->visits->count(),
'lastvisit' => $this->visits->max(),
'allvisits' => $this->visits,
'dateCreated' => Carbon::parse($this->created_at)->format('d/m/Y | h:i A'),
'dateUpdated' => Carbon::parse($this->updated_at)->format('d/m/Y | h:i A'),
];
}
for more info check https://laravel.com/docs/8.x/eloquent-resources