Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

Prido's avatar
Level 2

What is the best way when creating an api

What is the best way when creating an api. Restructuring i.e


$model_datas = Model::all();
$data =[];
$item =[];
foreach($model_datas as $model_data){
$item['id'] = $model_data->id;
$item['title'] = $model_data->title;
$item['created'] = $model_data->created_at;
$data[] = $item;
}

return json_encode($data);

OR just return


return json_encode($model_datas);

0 likes
1 reply
martinbean's avatar

@prido I don’t really know what you’re illustration, but you shouldn’t be fetching all records from your database, just to then iterate over them and try and JSON-encode them. If you have a lot of records, then you’re going to hit out-of-memory errors.

Instead, send paginated data sets to end users. And if you need to change the “shape” of records returned when they’re serialised as JSON, use Eloquent API resource classes to transform your models.

Please or to participate in this conversation.