API Resource — Laravel

An API Resource is a class that picks and tidies the fields (pairs of a key and a value) that leave a model as JSON. Create one with php artisan make:resource…

In plain PHP, before you turn one database row into JSON with json_encode($row), you usually build a new array first: take id, name and email, then drop the other columns. The member list, member detail and loan history endpoints each write that array themselves. Over time, the shapes of those three arrays become different.

An API Resource writes that shape once. An API Resource is a class that turns an Eloquent model into JSON, with a shape you decide yourself. Picture the member records on a librarian's desk. Each member's record sheet is complete: phone number, unpaid fines, whether the person is staff. The membership card in your pocket only shows your name, member number and the date you joined, laid out the same way for every member. In Laravel, the record sheet is the model: the full row from the database. The card printer is the resource: the resource picks which fields (pairs of a key and a value in the JSON) go out, then tidies their shape. The card is the JSON the client receives.

Why not return the model directly

Laravel can turn a model into JSON on its own, without a resource. This route returns the user with the id from the address, as it is:

Route::get('/api/users/{id}', fn ($id) => User::find($id));

For /api/users/1, the client receives Budi's data like this:

{"id":1,"name":"Budi","email":"[email protected]","phone":"081234567890","is_admin":0,"created_at":"2026-03-14T09:30:00.000000Z","updated_at":"2026-03-14T09:30:00.000000Z"}

password and remember_token are left out, because Laravel's default User model already marks both as hidden. But every other column comes along, and that causes three problems:

A resource does the opposite: only the fields you write go out.

Making a resource

Create the resource with Artisan:

php artisan make:resource UserResource

Then fill in the file like this:

<?php

namespace App\Http\Resources;

use Illuminate\Http\Request;
use Illuminate\Http\Resources\Json\JsonResource;

class UserResource extends JsonResource
{
    public function toArray(Request $request): array
    {
        return [
            'id' => $this->id,
            'name' => $this->name,
            'email' => $this->email,
            'member_since' => $this->created_at->format('Y-m-d'),
        ];
    }
}

One, many, and per page

A controller uses a resource in three ways. The data is three library members: Budi, Ani, Citra.

In the controller JSON the client receives
return new UserResource(User::find(1)); {"data":{"id":1,"name":"Budi","email":"[email protected]","member_since":"2026-03-14"}}
return UserResource::collection(User::all()); {"data":[{...Budi},{...Ani},{...Citra}]}
return UserResource::collection(User::paginate(2)); data holding Budi and Ani, plus links and meta

The resource the controller returns (the outermost resource) is always wrapped in a data key. So the JSON starts with {"data": {...}}, not straight with {"id": 1, ...}. For many models, use UserResource::collection(...), not new UserResource(...). The result of paginate(2) carries page details in links and meta:

"links": {
    "first": "http://127.0.0.1:8000/api/users?page=1",
    "last": "http://127.0.0.1:8000/api/users?page=2",
    "prev": null,
    "next": "http://127.0.0.1:8000/api/users?page=2"
},
"meta": { "current_page": 1, "from": 1, "last_page": 2, "path": "http://127.0.0.1:8000/api/users", "per_page": 2, "to": 2, "total": 3, "links": [...] }

On page 2, next becomes null and prev holds the address of page 1. How splitting results into pages works is covered in the Pagination lesson.

Conditional fields: when and whenLoaded

This is a toArray() with two fields that only go out under a condition:

return [
    'id' => $this->id,
    'name' => $this->name,
    'phone' => $this->when($request->user()?->is_admin, $this->phone),
    'loans' => LoanResource::collection($this->whenLoaded('loans')),
];

What gets checked in your UserResource

In the exercise, the starter code already has class UserResource extends JsonResource with an empty toArray($request). Fill the array with id, name, email and member_since. The exercise simulator loads the class and prints Class defined: UserResource. The class body is graded from the code: it must contain $this->..., ->format( and Y-m-d.

⚠️ Resources that error, slow down, or send raw dates

TL;DR: An API Resource is a class that picks and tidies the fields (pairs of a key and a value) that leave a model as JSON. Create one with php artisan make:resource UserResource, extend JsonResource, then return an array from toArray($request): 'id' => $this->id, 'member_since' => $this->created_at->format('Y-m-d'). Inside a resource, $this reads the model you give to the resource. A column you don't write never goes out. One model: return new UserResource($user). Many models: return UserResource::collection(User::all()). The result is wrapped in {"data": ...}, and paginate() adds page details in links and meta. $this->when(condition, value) drops its key from the JSON when the condition is false. $this->whenLoaded('loans') only shows a relation already loaded with with('loans').

⚡ Pick the fields that go out

Write:

class UserResource extends JsonResource
{
    public function toArray(Request $request): array
    {
        return [
            'id' => $this->id,
            'name' => $this->name,
            'email' => $this->email,
            'member_since' => $this->created_at->format('Y-m-d'),
        ];
    }
}

Meaning: An API Resource is a class that decides the JSON shape of a model. php artisan make:resource UserResource creates the class. Each key in the toArray() array becomes one field of the JSON. Inside a resource, $this reads the model you gave to the resource. Columns you don't write, such as phone and is_admin, never go out.

In the exercise, the date is formatted with ->format('Y-m-d'), and the order is id, name, email, member_since.

⚡ One or many

Write:

return new UserResource(User::find(1));
return UserResource::collection(User::all());
Guess first: toArray() returns ['id' => 1, ...]. Does the JSON from new UserResource(...) start straight with {"id": 1, ...}?

No. The JSON starts with {"data": {...}}. The resource the controller returns is always wrapped in a data key.

Meaning: One model uses new UserResource(...), many models use UserResource::collection(...). new UserResource(User::all()) errors, because a Collection (what all() returns) isn't one model.

⚡ Conditional fields

Meaning: Inside toArray(), 'phone' => $this->when(condition, value) sends the key phone out only when the condition is true. When it's false, that key is gone entirely. $this->whenLoaded('loans') only shows the loans relation when the controller already loaded it with with('loans'). When it isn't loaded, the key loans is gone and no extra query runs.

What you will learn