Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to serialize data from the database in laravel

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 :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading