Laravel

Lesson 07

API resources and response shape

Use API Resources to make public response fields explicit and keep model internals out of JSON responses.

Good Code

app/Http/Resources/ReviewResource.php
<?php

namespace App\Http\Resources;

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

final class ReviewResource extends JsonResource
{
    public function toArray(Request $request): array
    {
        // The resource owns the public JSON contract for a review.
        return [
            'id' => $this->id,
            'title' => $this->title,
            'rating' => $this->rating,
            'author' => $this->author->only(['id', 'name']),
        ];
    }
}

Bad Code

app/Http/Controllers/ReviewController.php
<?php

public function index()
{
    // Returning models directly exposes fields whenever the model changes.
    return Review::with('author')->latest()->get();
}

Review Notes

What to review

Good Code

The good version names the response fields in a Resource class. The controller can return a stable API contract while the model stays free to change internally.

Bad Code

The bad version returns Eloquent models directly. New columns, hidden fields, or relationships can change the API without a focused review.

Takeaways

  • Responses should expose a deliberate shape instead of leaking every model field and relationship.