Source: juststeveking.uk

JSON API Resources in Laravel
Building APIs in Laravel is a passion of mine, and I have spent a lot of time searching for the perfect way to return consistent JSON:API friendly resources so that I can find and use a standard. The negatives outweighed the benefits of this approach, as the development time spent achieving it just felt like it wasn’t worth it.

It allows us to build and return JSON:API compliant resources that are easy to use.

Previously we would do something similar to: return [ 'id' => $this->id, 'type' => 'post', 'attributes' => [ 'title' => $this->title, 'slug' => $this->slug, 'content' => $this->content, ], 'relationships' => [ 'category' => new CategoryResource( resource: $this->whenLoaded('category'), ), ]]; This isn’t a bad way to do it by any means; however, let us have a look at how we would add these on the JSON:API package: protected function toRelationships(Request $request): array { return [ 'category' => fn () => new CategoryResource( resource: $this->category, ), ]; }

The JSON:API package has an alternative approach, which is particularly fluent: protected function toLinks(Request $request): array { return [
Newsletter

Get the latest Laravel/PHP jobs, events and curated articles straight to your inbox, once a week

Fathom Analytics | Fast, simple and privacy-focused website analytics. Fathom Analytics | Fast, simple and privacy-focused website analytics.
Achieve superior email deliverability with ToastMail! Our AI-driven tool warms up inboxes, monitors reputation, and ensures emails reach their intended destination. Sign up today for a spam-free future. Achieve superior email deliverability with ToastMail! Our AI-driven tool warms up inboxes, monitors reputation, and ensures emails reach their intended destination. Sign up today for a spam-free future.
Community Partners