shortcode - Change fields in a Laravel API Resource via transform

Laravel makes forming data for an API response easier using API Resources, which take data (usually queried from Models), and return specific fields and structure you define. Resource Collections are what they sound like, they're collections of resources. Collections would be used for pages like an archive, where you have more than one item to display from your model.

The only issue you may encounter with Resource Collections is that they'll display all the item data, and won't allow you to exclude fields manually. Usually you don't need every field when you query an archive, just the vital info (title, slug, maybe tags) -- and let the user query the individual item for the rest of the fields.

This code snippet leverages the transform() method from Laravel's Collection wrapper (different from Resource Collections) to limit the response to set fields:

<?php
class PageResourceCollection extends ResourceCollection
{
    public function toArray($request)
    {
        return [
            'data' => $this->collection->transform(function($page){
                return [
                    'id' => $page->id,
                    'title' => $page->title,
                    'slug' => $page->slug,
                ];
            }),
        ];
    }
}

Hope that helps, Ryo


References

Leave a comment