0Pricing
PHP Academy · Lesson

API Resources and JSON Responses

Shape JSON output with Eloquent API Resources and ResourceCollections.

API Resources and JSON Responses is a free PHP Academy lesson on CoddyKit — lesson 2 of 4. You can read the complete lesson below for free — then practise it hands-on in the browser with a built-in code editor and a 24/7 AI tutor. It is part of the PHP Academy learning path, one of 4 lessons in the course, and your progress syncs across the web and the CoddyKit app.

What Are API Resources?

Eloquent API Resources transform models and collections into JSON-ready arrays, giving you full control over the shape of your API responses.

Generating a Resource

Create a resource class with Artisan.

$ php artisan make:resource UserResource
# For collections:
$ php artisan make:resource UserCollection

Basic Resource

Override toArray() to define the JSON structure.

<?php
namespace App\Http\Resources;

use Illuminate\Http\Resources\Json\JsonResource;

class UserResource extends JsonResource
{
    public function toArray($request): array
    {
        return [
            "id"         => $this->id,
            "name"       => $this->name,
            "email"      => $this->email,
            "created_at" => $this->created_at->toISOString(),
        ];
    }
}

Returning a Resource

Return the resource from a controller — it automatically wraps the model in a data key.

<?php
public function show(User $user): UserResource
{
    return new UserResource($user);
}
// Response: {"data": {"id": 1, "name": "Alice", ...}}

Resource Collections

Wrap a collection of models with ::collection().

<?php
public function index(): AnonymousResourceCollection
{
    return UserResource::collection(User::paginate(15));
}

Conditional Fields

Include a field only when a condition is met using when().

<?php
return [
    "id"    => $this->id,
    "email" => $this->when($request->user()?->isAdmin(), $this->email),
    "token" => $this->whenLoaded("tokens", $this->tokens->first()->plainTextToken),
];

whenLoaded()

Conditionally include a relationship only if it has already been loaded — avoids N+1 in resource responses.

<?php
return [
    "id"      => $this->id,
    "posts"   => PostResource::collection($this->whenLoaded("posts")),
    "profile" => new ProfileResource($this->whenLoaded("profile")),
];

Nested Resources

Nest resources inside other resources for rich, typed response shapes.

<?php
return [
    "id"     => $this->id,
    "author" => new UserResource($this->author),
    "tags"   => TagResource::collection($this->tags),
];

Additional Meta Data

Add metadata to the response by overriding with().

<?php
public function with($request): array
{
    return [
        "meta" => ["version" => "1.0"],
    ];
}

Wrapping

By default, resources are wrapped in a data key. Disable wrapping globally with JsonResource::withoutWrapping().

<?php
// In AppServiceProvider::boot():
JsonResource::withoutWrapping();

Pagination in Resources

Pagination metadata is automatically included when you pass a paginator to a resource collection.

<?php
return UserResource::collection(User::paginate(15));
// Response includes: data[], links{}, meta{}

Testing Resources

Assert resource structure in tests with assertJson() or assertJsonStructure().

<?php
$response->assertJsonStructure([
    "data" => ["id", "name", "email"]
]);

Summary

API Resources control your JSON output shape. Use when() and whenLoaded() for conditional fields. Nest resources for relationships. Use ::collection() for multiple models.

Quick Check

Which method conditionally includes a relationship only if already loaded?

Frequently asked questions

Is the “API Resources and JSON Responses” lesson free?

Yes — the full text of “API Resources and JSON Responses” is free to read here on the web, and the PHP Academy course includes 4 lessons in total. To practise it interactively (a built-in code editor and a 24/7 AI tutor) and unlock the rest of the PHP Academy course, upgrade to CoddyKit PRO.

What will I learn in “API Resources and JSON Responses”?

Shape JSON output with Eloquent API Resources and ResourceCollections. You practise PHP Academy with hands-on code you run directly in the browser, and a 24/7 AI tutor answers your questions as you work through the lesson.

Do I need any experience to start PHP Academy?

No prior experience is required. PHP Academy on CoddyKit is structured for beginners through advanced learners; this is — lesson 2 of 4, so you can start here or from the beginning and move at your own pace.

How long does the “API Resources and JSON Responses” lesson take?

Most CoddyKit lessons take about 5–10 minutes. Each one is bite-sized and interactive, so you make steady progress and pick up exactly where you left off across the web and the app.

Can I write and run code in this PHP Academy lesson?

Yes. Every PHP Academy lesson includes a built-in code editor, so you write and run real code right in your browser and get instant AI feedback — no local setup required.

All lessons in this course

  1. API Routes and Resource Controllers
  2. API Resources and JSON Responses
  3. Authentication with Laravel Sanctum
  4. Rate Limiting and API Versioning
← Back to PHP Academy