Skip to content

Custom TransformerableAbstract class

Cyvelnet edited this page Oct 11, 2017 · 1 revision

Sometimes there are common functions share in transformer classes, now you may create your custom class and extends \League\Fractal\TransformerAbstract and instruct transformer generator to use your custom class by making changes in config/fractal.php

  1. Create your custom class
namespace App;

class MyCustomClass extends \League\Fractal\TransformerAbstract{

    // put common include methods
    public function includeAuthor(Product $product){
        return $this->item($product->author, new AuthorTransformer);
    }
    ...

    // put common formatting methods
    public function formatDate($date){
        return $date->format('M d,Y');
    }

    // some other function ...

}
  1. Edit abstract_parent in config/fractal.php
...
'abstract_parent' => App\MyCustomClass::class, // FQCN 
...
  1. Use php artisan make:transformer command normally, issue a php artisan config:cache in case you have config cached.

  2. Now for every transformer, our custom class will be use instead.