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
‹ swipe to step through ›
Walkthrough
Space play
←→ step
click any line
Three takeaways
- 1API Resources decouple your database schema from the JSON shape clients actually receive.
- 2Conditional helpers like whenLoaded and when keep payloads lean and avoid triggering lazy queries.
- 3Deriving values in the transformer keeps computation out of controllers and consistent across endpoints.
Related explainers
php
<?php class NameParser {
Parsing a full name into components in PHP
string-parsing
arrays
normalization
Intermediate
8 steps
php
<?php namespace App\Services\Checkout;
Validating coupons with Laravel's Pipeline
pipeline
chain of responsibility
transactions
Intermediate
7 steps
php
<?php namespace App\Services;
How a password strength validator works in PHP
validation
regular-expressions
data-driven
Intermediate
8 steps
rust
use axum::{ extract::{Path, State}, response::sse::{Event, KeepAlive, Sse}, };
Streaming import progress with SSE in Axum
server-sent-events
streams
watch-channel
Advanced
7 steps
php
<?php namespace App\Services;
Building a cached daily leaderboard in Laravel
caching
aggregation
eager-loading
Intermediate
9 steps
php
<?php final class RotatingFileLogger {
How a rotating file logger works in PHP
logging
file-rotation
io
Intermediate
9 steps
Share this explainer
Here's the card — post it anywhere.
Made with highlit — turn any snippet into a walkthrough like this in about a minute.
Explain your code
Embed this explainer
Drop the interactive walkthrough into a blog or docs. Views never cost a credit.
<iframe src="https://highlit.co/explainers/shaping-api-json-with-a-laravel-resource-explained-php-e276/embed?autoplay=1" width="100%" height="520" loading="lazy" style="border:0"></iframe>
Autoplay is on by default — add ?autoplay=0 to start paused.