Laravel-fractal v2 has been released original

by Freek Van der Herten – 1 minute read

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());

$manager->createData($resource)->toArray();

Laravel-fractal makes that a lot easier:

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

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
})->toArray();

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.

Join 9,500+ smart developers

Get my monthly newsletter with what I learn from running Spatie, building Oh Dear, and maintaining 300+ open source packages. Practical takes on Laravel, PHP, and AI that you can actually use.

No spam. Unsubscribe anytime. You can also follow me on X.

Found something interesting to share? Submit a link to the community section.