Laravel API Resource transform model to JSON response
PHP Dasun Kalupahana 103 views
<?php
// php artisan make:resource PostResource
namespace App\Http\Resources;
use Illuminate\Http\Request;
use Illuminate\Http\Resources\Json\JsonResource;
class PostResource extends JsonResource
{
public function toArray(Request $request): array
{
return [
'id' => $this->id,
'title' => $this->title,
'author' => new UserResource($this->whenLoaded('author')),
'created' => $this->created_at->toIso8601String(),
];
}
}
// Controller
return PostResource::collection(Post::with('author')->paginate(15));
Controls exactly which fields your API returns, so you never leak columns by accident. whenLoaded includes a relation only if it was eager loaded, which avoids extra queries.
Learn more on the blog
MySQL
PostgreSQL vs MySQL Performance: Real Benchmarks Compared
Last updated: 7 November 2026. See the update log at the end."Which...
8 min read
PHP
How to Detect and Fix PHP Memory Leaks
Last updated: 5 November 2026. See the update log at the end.In...
9 min read
Docker
Docker Build Too Slow? 10 Ways to Speed It Up
A slow Docker build usually has one of a few causes: you...
8 min read