SyntaxStudy
Sign Up
PHP Laravel API Resources
PHP Intermediate 4 min read

Laravel API Resources

Eloquent API Resources

Laravel API Resources transform Eloquent models into JSON-serialisable arrays with full control over field exposure.

Example
// 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));
Pro Tip

API Resources prevent accidentally exposing password_hash or other sensitive fields in JSON output.