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.
Lesson 07
Use API Resources to make public response fields explicit and keep model internals out of JSON responses.
<?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']),
];
}
}<?php
public function index()
{
// Returning models directly exposes fields whenever the model changes.
return Review::with('author')->latest()->get();
}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.
The bad version returns Eloquent models directly. New columns, hidden fields, or relationships can change the API without a focused review.