Every two weeks I send out a newsletter containing lots of interesting stuff for the modern PHP developer. You can expect quick tips, links to interesting tutorials, opinions and packages. Want to learn the cool stuff? Then sign up now!

A Fractal service provider for Laravel

Today I released a new package called laravel-fractal. It provides a Fractal service provider for Laravel. 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 League\Fractal\Manager;
use League\Fractal\Resource\Collection;

$fractal = new Manager();

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

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

$array = $fractal->createData($resource)->toArray();

The laravel-fractal package makes that process a tad easier:

   ->transformWith(new BookTransformer())

The package has support for Fractal’s serializers. All available options are explained in the readme.

If you like this package, take a look at the other Laravel packages our team has previously released.

Freek Van der Herten is a partner and developer at Spatie, an Antwerp based company that specializes in creating web apps with Laravel. After hours he writes about modern PHP and Laravel on this blog. When not coding he’s probably rehearsing with his kraut rock band.
  • Love fractal <3

  • Eric

    I may be missing something, but is there a way to set the Fractal paginator? For instance:

    $paginator = Book::whereActive(1)->paginate(10);
    $books = $paginator->getCollection();

    ->transformWith(new BookTransformer())
    ->paginateWith(new IlluminatePaginatorAdapter($paginator))

    • Pagination is not (yet) supported. I’ll add it sometime in near future. If you need this quick, feel free to submit a PR.