How to Start using Transformers in Laravel

Haydar Ali Ismail
2 min readJan 15, 2017

--

Laravel is one of a popular PHP framework out there. Laravel also happened to use REST paradigm by nature. Today, I’m going to write a story about creating a simple transformer in Laravel. This story assumes you already know the basic of Laravel.

How We Usually Do It

Usually, when we create a JSON response in Laravel, we would use our model.

Let’s say we want to fetch the firstUser in JSON, then we probably would use something like this.

Boom! Now you get a JSON response of the first user registered on your web app. But, what if develop further than the model change? Then the JSON response also changes. That’s fine at some point, but what if you still have to support mobile applications or other application clients that rely on the old JSON response with a specific scheme? That’s where Transformers fits in.

Transformers

Basically, transformers give you the flexibility to create a format for JSON response that you need. By using transformers we can also do type casting, pagination results, and also nest relationships.

If you used Dingo API then the Fractal Transformers module already installed. Otherwise you can install it yourself by installing Fractal.

Writing a transformer is easy, here is an example of a transformer for the User model we have earlier.

Then, when we only need to call the transformer with something like the snippet below. If you use Dingo or want to show the result in DataTable you will need to do it in their way, check their documentation for further instruction.

You might think that currently the returned response still the same compared to the one from the ordinary method. But, in long term, you will thank me later. We will continue to discuss this matter in future stories.

Wrap Up

Today, we have talked about how to create JSON response from Transformer. One of the flexibility of using transformer is that it is not directly derived from the model class. Thus, API versioning or creating transformer for the same model with different purposes would be easier. In future stories, we will discuss more about how to maximize the capabilities of transformers in Laravel. Thanks for reading.

--

--