Yeah, that JSON structure you're using is pretty heavy. JSON:API solves some problems, but for most Laravel apps it just adds a lot of noise. If you don’t really need JSON:API compatibility, you can go with something much cleaner and easier to work with. A common pattern is:
// Example list response:
{
"data": [
{
"id": 1,
"foo": "bar"
}
]
}
// Example show response with an included author:
{
"data": {
"id": 1,
"title": "Bug in checkout",
"description": "Steps to reproduce...",
"status": "open",
"author": {
"id": 5,
"name": "Jeremy",
"email": "jeremy@example.com"
}
}
}
// Nice and clean, no extra layers.
A simpler TicketResource example:
public function toArray(Request $request): array
{
return [
'id' => $this->id,
'title' => $this->title,
'description' => $this->when(
$request->routeIs('tickets.*'),
$this->description
),
'status' => $this->status,
// Include relationship only if it's loaded
'author' => new UserResource($this->whenLoaded('author')),
// Optional links if you like that style
'links' => [
'self' => route('tickets.show', $this->id),
'author' => $this->when(
$this->relationLoaded('author'),
fn () => route('authors.show', $this->author->id)
),
],
];
}
// Controller example
$tickets = Ticket::query()
->when($request->boolean('include_author'), fn ($q) => $q->with('author'))
->paginate();
return TicketResource::collection($tickets);
There’s no official Laravel standard for API shape but this lighter style is extremely common and much easier to maintain. If you don’t need strict JSON:API rules, going simpler is usually the better
Sign in to participate in this thread!
The Laravel portal for problem solving, knowledge sharing and community building.