Source: paulreaney.medium.com

Laravel API resources

Category: Laravel, api

As a Laravel developer you may be familiar with packages like this https://fractal.thephpleague.com/transformers/ however Laravel now has API resources built in since version 5.5 and over time many people have switched over. Of course you can convert models or c ollections to JSON using their toJson method, however a transformer will give you more control over the JSON serialization of your models and their relationships.

We can return anything we want by using the with() method in the resource class: This now returns sibling data alongside our vehicle data — which could be whatever you like: We may want to return some fields but not others, or change the names of the fields for public consumption. In that case we can specify exactly what we do want to return by specifying the fields in the toArray() method: In this case I changed the ‘model’ name to ‘model_name’ and removed any date fields to stop those from being returned.

To load a collection of objects you can use the static collection method: This will load data as an array of vehicles: Or you can create a new resource collection.
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