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.
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.
collection method will take a collection of records to be transformed and make sure to instantiate a new
UsersResource for each record.
Two key pieces here: attribute accessor and optional nested transformation
Resourceclass it is possible to have direct access to the model attributes via
$this. This magic is done in the
DelegatesToResourcetrait that is included in the base
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
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.
Level up your reading game by joining Hacker Noon now!