Appearance
JSON resource
scope
This document doesn't include rules to build public APIs
Structure
- Resources should be simple data transformers
- Assert resource type in toArray method for better static analysis
- Keep transformation logic minimal
Example:
php
use Illuminate\Http\Resources\Json\JsonResource;
/** @property-read \App\Modules\Course\Models\Course $resource */
final class CourseResource extends JsonResource
{
public function toArray(Request $request): array
{
$course = $this->resource;
assert($course instanceof \App\Modules\Course\Models\Course);
return [
'id' => $course->id,
'name' => $course->title,
'slug' => $course->slug,
'level' => $course->level->value,
'created_at' => $course->created_at->toIso8601String(),
];
}
}Naming
- Use clear, descriptive names that indicate the model being transformed
- Follow Laravel's convention of suffixing with "Resource"
- Use "Collection" suffix for collection resources if needed
Response Structure
- Keep the response structure consistent across similar resources
- Include only the necessary fields for the client
- Use different Resource classes for the same Model (e.g. for public and private representation of a resource)
- Use proper data types (string for IDs, boolean for flags, etc.)