php 32 lines · 7 steps

Shaping API JSON with a Laravel Resource

An API Resource transforms an Order model into a clean, computed JSON payload for clients.

Explained by highlit
1<?php
2 
3namespace App\Http\Resources;
4 
5use Illuminate\Http\Request;
6use Illuminate\Http\Resources\Json\JsonResource;
7 
8class OrderResource extends JsonResource
9{
10 public function toArray(Request $request): array
11 {
12 return [
13 'id' => $this->id,
14 'reference' => $this->reference,
15 'status' => $this->status,
16 'currency' => $this->currency,
17 'subtotal' => $this->subtotal,
18 'tax' => $this->tax,
19 'shipping' => $this->shipping,
20 'total' => $this->subtotal + $this->tax + $this->shipping,
21 'item_count' => $this->whenLoaded('items', fn () => $this->items->sum('quantity')),
22 'is_paid' => $this->paid_at !== null,
23 'paid_at' => $this->paid_at?->toIso8601String(),
24 'estimated_delivery' => $this->when(
25 $this->status === 'shipped' && $this->shipped_at,
26 fn () => $this->shipped_at->addDays(5)->toDateString(),
27 ),
28 'customer' => new CustomerResource($this->whenLoaded('customer')),
29 'created_at' => $this->created_at->toIso8601String(),
30 ];
31 }
32}
01 / 01
STEP 01

Walkthrough

Space play step click any line
Three takeaways
  1. 1API Resources decouple your database schema from the JSON shape clients actually receive.
  2. 2Conditional helpers like whenLoaded and when keep payloads lean and avoid triggering lazy queries.
  3. 3Deriving values in the transformer keeps computation out of controllers and consistent across endpoints.

Related explainers

Share this explainer

Here's the card — post it anywhere.

Shaping API JSON with a Laravel Resource — share card
Made with highlit — turn any snippet into a walkthrough like this in about a minute.
Explain your code