Add Fractal service provider in Laravel 5 and Lumen

In this  article i will show you how to add fractal service provider in Laravel 5 and Lumen , before i get started do you know what fractal is ? dont worry  checkout these docs or in short Fractal is very useful to transform data before using it in an API. for this we will be using a laravel package called  laravel-fractal The package provides a nice and easy integration with Fractal for your Laravel 5 and Lumen projects. If you don’t know what Fractal does, take a peek at their intro. Shortly said, Fractal is very useful to transform data before using it in an API.


Using Fractal data can be transformed like this:

use LeagueFractalManager;
use LeagueFractalResourceCollection;

$books = [
   ['id'=>1, 'title'=>'Hogfather', 'characters' => [...]], 
   ['id'=>2, 'title'=>'Game Of Kill Everyone', 'characters' => [...]]

$manager = new Manager();

$resource = new Collection($books, new BookTransformer());



This package makes that process a tad easier:

   ->transformWith(new BookTransformer())

Lovers of facades will be glad to know that a facade is provided:

Fractal::collection($books)->transformWith(new BookTransformer())->toArray();

so lets get started with installation

You can pull in the package via composer:

$ composer require spatie/laravel-fractal

Next up, the service provider must be registered:

// Laravel5: config/app.php
'providers' => [


or, if you are using Lumen:

// Lumen: bootstrap/app.php

If you want to make use of the facade you must install it as well:

// config/app.php
'aliases' => [
    'Fractal' => SpatieFractalFractalFacade::class,

If you want to change the default serializer, you must publish the config file:

php artisan vendor:publish --provider="SpatieFractalFractalServiceProvider"

This is the contents of the published file:

return [

     * The default serializer to be used when performing a transformation.
     * Leave empty to use the Fractal's default.
    'default_serializer' => '',


In the following examples were going to use the following array as example input:

$books = [['id'=>1, 'title'=>'Hogfather'], ['id'=>2, 'title'=>'Game Of Kill Everyone']];

But know that any structure that can be looped (for instance a collection) can be used.

Recommended :  See Who's Online in your laravel app

Let’s start with a simple transformation.

   ->transformWith(function($book) { return ['id' => $book['id']];})

This will return:

['data' => [['id' => 1], ['id' => 2]]

Instead of using a closure you can also pass a Transformer:

   ->transformWith(new BookTransformer())

To make your code a bit shorter you could also pass the transform closure or class as a second parameter of the collection-method:

fractal()->collection($book, new BookTransformer())->toArray();

Want to get some sweet json output instead of an array? No problem!

fractal()->collection($book, new BookTransformer())->toJson();

A single item can also be transformed:

fractal()->item($book[], new BookTransformer())->toArray();

Using a serializer

Let’s take a look again a the output of the first example:

['data' => [['id' => 1], ['id' => 2]];

Notice that data-key? That’s part of Fractal’s default behaviour. Take a look at Fractals’s documentation on serializers to find out why that happens.

Recommended :  FOSJSRoutingBundle in symfony

If you want to use another serializer you can specify one with the serializeWith-method. The SpatieFractalArraySerializer comes out of the box. It removes the data namespace for both collections and items.

   ->transformWith(function($book) { return ['id' => $book['id']];})
   ->serializeWith(new SpatieFractalArraySerializer())

//returns [['id' => 1], ['id' => 2]]

Changing the default serializer

You can change the default serializer by providing the classname of your favorite serializer in the config file.

Using includes

Fractal provides support for optionally including data on the relationships for the data you’re exporting. You can use Fractal’s parseIncludes which accepts a string or an array:

   ->collection($this->testBooks, new TestTransformer())
   ->parseIncludes(['characters', 'publisher'])

To improve readablity you can also a function named include followed by the name of the include you want to… include:

   ->collection($this->testBooks, new TestTransformer())

Using pagination

Fractal provides a Laravel-specific paginator, IlluminatePaginatorAdapter, which accepts an instance of Laravel’s LengthAwarePaginator and works with paginated Eloquent results. When using some serializers, such as the JsonApiSerializer, pagination data can be automatically generated and included in the result set:

$paginator = Book::paginate(5);
$books = $paginator->getCollection();

    ->collection($books, new TestTransformer())
    ->serializeWith(new JsonApiSerializer())
    ->paginateWith(new IlluminatePaginatorAdapter($paginator))

Setting a custom resource name

Certain serializers wrap the array output with a data element. The name of this element can be customized:

    ->collection($this->testBooks, new TestTransformer())
    ->serializeWith(new JsonApiSerializer())
    ->item($this->testBooks[], new TestTransformer(), 'book')
    ->serializeWith(new JsonApiSerializer())


Recommended :  How to enable HTML5 routing in angularjs - quick tip

About the author

Deven Rathore

I'm Deven Rathore, a multidisciplinary & self-taught designer with 3 years of experience. I'm passionate about technology, music, coffee, traveling and everything visually stimulating. Constantly learning and experiencing new things.

  • Darryl Friesen

    This isn’t an “article” that will show me how to “add fractal service provider in Laravel 5 and Lumen”. It’s a copy-paste of the the README from the spatie/laravel-fractal project. (See

Pin It on Pinterest