📡 You're offline — showing cached content
New version available!
Quick Access
Tutorials Laravel Framework API Resources

API Resources

5 min read Quiz at the end
Shape API responses with JsonResource — control output fields, hide sensitive data, and format collections.

API Resources

php artisan make:resource UserResource
php artisan make:resource UserCollection

class UserResource extends JsonResource {
    public function toArray(Request $request): array {
        return [
            "id"         => $this->id,
            "name"       => $this->name,
            "email"      => $this->email,
            "role"       => $this->role,
            "created_at" => $this->created_at->toIsoString(),
            "posts_count"=> $this->whenCounted("posts"),
            "posts"      => PostResource::collection(
                                $this->whenLoaded("posts")
                            ),
        ];
    }
}

// In controller
return new UserResource($user);
return UserResource::collection(User::paginate(10));

// API response format
// {
//   "data": { "id": 1, "name": "Alice" },
//   "meta": { "current_page": 1, "total": 50 }
// }
Topic Quiz · 2 questions

Test your understanding before moving on

1. What is the purpose of API Resources?
💡 API Resources control exactly what data is exposed in your API JSON responses.
2. Which method wraps a collection with a resource?
💡 UserResource::collection($users) wraps a collection with the resource transformation.