Back to All Nuggets
Laravel php ⏱️ 2 min read
Production Implementation
Ask endoAI
<?php

declare(strict_types=1);

namespace App\Http\Resources;

use Illuminate\Http\Request;
use Illuminate\Http\Resources\Json\JsonResource;

class CourseDetailResource extends JsonResource
{
    public function toArray(Request $request): array
    {
        return [
            'id' => $this->id,
            'title' => $this->title,
            'slug' => $this->slug,
            'summary' => $this->summary,
            'price' => [
                'amount' => (float)$this->price,
                'currency' => $this->currency ?? 'KES',
                'formatted' => 'KES ' . number_format((float)$this->price, 2),
            ],
            'modules' => CourseModuleResource::collection($this->whenLoaded('modules')),
            'published_at' => $this->created_at?->toIso8601String(),
        ];
    }
}

Protecting Internal Schemas and Formatting Production JSON APIs

Returning raw Eloquent models directly from controller endpoints is a security vulnerability. It exposes internal column names, timestamps, and sensitive fields. Eloquent API Resources provide a robust transformation layer.

Benefits

  • Decoupled Schema: Modify tables without breaking frontend clients.
  • Prevent N+1 Queries: Conditionally load relationships using $this->whenLoaded().
  • Standard Envelopes: Uniformly format currency, dates, and calculated statistics.

Accelerate Your Engineering Career

Get monthly masterclasses, exclusive code snippets, and direct architectural reviews.

Become a Supporter • KES 500 / Month