Eloquent API Resources
Laravel API Resources transform Eloquent models into JSON-serialisable arrays with full control over field exposure.
Laravel API Resources transform Eloquent models into JSON-serialisable arrays with full control over field exposure.
// php artisan make:resource UserResource
class UserResource extends JsonResource {
public function toArray($request): array {
return [
"id" => $this->id,
"name" => $this->name,
"email" => $this->email,
"role" => $this->role,
"links" => ["self" => route("users.show", $this->id)],
];
}
}
// In controller:
return UserResource::collection(User::paginate(15));
API Resources prevent accidentally exposing password_hash or other sensitive fields in JSON output.