Awwwards
Announcing the Laravel Transformer Maker! 's Hero Image

Announcing the Laravel Transformer Maker!

Following up last week's post on building a decent API, I found myself getting incredibly annoyed at how tedious it was to create a new Transformer file to play nice with Fractal. Sure, copy and paste isn't the worst thing in the world, but I still ran into problems. For instance, I would inevitably miss a variable name, or not change the injected model and it frustrated me to no end.

So, if you're deep into creating a Fractal-friendly API, you've no doubt encountered the need to create Transformers that play nice with your Eloquent models. I noticed this earlier in the week when my workflow was the following:

php artisan make:model Person -m
php artisan make:controller PeopleController
php artisan make:test features/PeopleControllerTest

// PhpStorm
1. create empty file
2. find existing Transformer file
3. copy Transformer
4. paste into empty file
5. change references from Animal to Person
6. change variables from $animal to $person
7. remove $availableIncludes and related functions
8. update attributes in transformed array

I would write the test and begin implementing features only to find I'd imported the wrong model, or I didn't change a variable, or there's a typo, or some other mindless, stupid mistake.

Why couldn't I just automate it?

Oh but I could. Thus started my deep dive into the GeneratorCommand in the Laravel framework and looking into how make:controller works. And it's not bad at all.

Now, my workflow is:

php artisan make:model Person -m
php artisan make:controller PeopleController
php artisan make:test features/PeopleControllerTest
php artisan make:transformer Person

And, voila! A fully stubbed out transformer shows up in App\Transformers as PersonTransformer.php. And it even has links in the transformed array so you can start implementing HATEOAS right off the bat!

Installation and Usage

Issue the command:

composer require "metricloop/laravel-transformer-maker"

Then register the service provider:

// config/app.php

'providers' => [
    // ...
    MetricLoop\TransformerMaker\TransformerMakerServiceProvider::class,
];

Then just use it like any other Artisan make command:

php artisan make:transformer Person

And get the stubbed out PersonTransformer.php in App/Transformers!

Note: the stubbed transformer file depends on you having the League\Fractal package installed.

Check it out on GitHub!


Patrick Guevara's Profile Picture

Patrick Guevara


Chief Software Engineer

Patrick cofounded Metric Loop on the dream of building really great software with a clean, transparent approach. He lives in Austin, Texas with his wife Jess and their dog named Moose.