Reusable API Resource with Nested Relationship — Laravel 5.5

Written by deleugpn | Published 2017/08/26
Tech Story Tags: laravel | software-development | api | development

TLDRvia the TL;DR App

Two days ago I published my first impressions on Laravel newest API Resource feature. This article will take one step further by using a more Laravel-friendly approach in the Transformation layer.

Note: This article will start at step 4. Steps 1~3 will be the same as in the previous article (models, migrations, database, environment setup). You can check it out clicking here.

4- Renaming the Resource (fixing legacy)

The previous article creates a resource called UsersWithPostsResource. Let’s rename it to UsersResource and learn how it is possible to reuse it on the following steps.

5- Using API Resource inside your controller

The static collection method will take a collection of records to be transformed and make sure to instantiate a new UsersResource for each record.

6- The UsersResource class

Two key pieces here: attribute accessor and optional nested transformation

  • Inside a Resource class it is possible to have direct access to the model attributes via $this. This magic is done in the DelegatesToResource trait that is included in the base Resource class.
  • It is possible to transform a relationship if the data is available (eager loaded) or ignore it in case it hasn’t been loaded yet. This will prevent N+1 problems while still being able to handle different scenarios with a single Resource class. If the relationship is not available, it will be ignored, otherwise included.

7- Posts Resource

8- Conclusion

Keeping it simple and one step at a time, the focus of this article is to improve the knowledge gathered from the last one by learning to use Resource::collection instead of manually instantiating the classes and also to delegate to the controller the responsibility of giving (or not) the relationship data. By simply removing with('posts') from the controller, the API will no longer include the posts of each user in the response.

While Fractal would offer default and available includes inside the Transformer layer, the native API Resource on Laravel will prefer to have the Controller handling that logic. After all, it is the controllers’ job to understand the request.

In the next article I intend to implement a way for the user of the API to request a relationship to be included. Consider following me on Medium for more articles like this.


Published by HackerNoon on 2017/08/26