Oh Dear is the all-in-one monitoring tool for your entire website. We monitor uptime, SSL certificates, broken links, scheduled tasks and more. You'll get a notifications for us when something's wrong. All that paired with a developer friendly API and kick-ass documentation. O, and you'll also be able to create a public status page under a minute. Start monitoring using our free trial now.

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.

Share Post LinkedIn

I write about Laravel, PHP, AI and building better software.

Every two weeks, I share practical tips, tutorials, and behind-the-scenes insights from maintaining 300+ open source packages. Join thousands of developers who read along.

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

Found something interesting to share?

The community section is a place where developers share links to articles, tutorials and videos. Submit a link and help fellow developers discover great content. As a thank you, you'll receive a coupon for a discount on Spatie products.