Skip to content

Transformable Trait

Cyvelnet edited this page Oct 11, 2017 · 4 revisions

With the assists of artisan command php artisan make:transformer UserTransformer -m User, it makes data serialization and transformation a breeze but writing Fractal::item($data, new DataTransformer) and Fractal::collection($data, new DataTransformer) is become a pain as application grow and now a new Transformable Trait is here to join the fun.

use App\Http\Controllers\Controller;
use App\Transformers\UserTransformer;

public class UserController extends Controller
{

// it should goes to the base Controller class, but for demostration purpose lets have it here
use \Cyvelnet\Laravel5Fractal\Traits\Transformable;

    // override default serialize in class scope
    // protected $serializer =  \Acme\My\CustomSerialize::class;

    protected $transformer = UserTransformer::class;

    public function index(){

        return $this->transform(User::paginate());

    }


    public function show($id){

        return $this->transform(User::find($id));

    }

}

Refer to the example above, the transformation look shorter and easier to read, no item() or collection() and no duplicated new UserTransformer() all over the controller.

Clone this wiki locally