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!

Laravel-fractal v2 has been released

Last week v2 of laravel-fractal was released. This package is a developer friendly wrapper around the League’s Fractal package. It a Laravel context it can be used to transform your Eloquent models to JSON output for an API. Think of it as toJson (or toArray) on steroids.

This is how you can work with the league’s package:

use League\Fractal\Manager;
use League\Fractal\Resource\Collection;

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

$manager = new Manager();

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


Laravel-fractal makes that a lot easier:

   ->transformWith(new BookTransformer())

With the newly tagged v2 of our package you can compact that code to this:

fractal($books, new BookTransformer())->toArray();

You can even pass in a callable as a second argument.

fractal($books, function(Book $book) {
   // do your transforming here

Fractal and laravel-fractal can do a whole lot more. Head over to the docs on GitHub to learn all the options.

If you were already using v1 of the package, it’s fairly easy to upgrade to v2.

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.
  • Bonzo

    Is it possible you write a post where you can describe a real-world example using this package and the fractal-package in general ?

  • To be honest, I’ve never like the way Fractal being use . Just because I hate using `new` 😀