PHPackages                             andrewmclagan/laravel-fractal - PHPackages - PHPackages  [Skip to content](#main-content)[PHPackages](/)[Directory](/)[Categories](/categories)[Trending](/trending)[Leaderboard](/leaderboard)[Changelog](/changelog)[Analyze](/analyze)[Collections](/collections)[Log in](/login)[Sign up](/register)

1. [Directory](/)
2. /
3. [API Development](/categories/api)
4. /
5. andrewmclagan/laravel-fractal

ActiveLibrary[API Development](/categories/api)

andrewmclagan/laravel-fractal
=============================

An easy to use Fractal integration for Laravel applications

5.3.0(8y ago)029MITPHPPHP ^7.0

Since Oct 6Pushed 8y agoCompare

[ Source](https://github.com/andrewmclagan/laravel-fractal)[ Packagist](https://packagist.org/packages/andrewmclagan/laravel-fractal)[ Docs](https://github.com/spatie/laravel-fractal)[ RSS](/packages/andrewmclagan-laravel-fractal/feed)WikiDiscussions master Synced yesterday

READMEChangelogDependencies (5)Versions (49)Used By (0)

An easy to use Fractal wrapper built for Laravel applications
=============================================================

[](#an-easy-to-use-fractal-wrapper-built-for-laravel-applications)

[![Latest Version on Packagist](https://camo.githubusercontent.com/2c8abd7a8dbe9de160541bf2533a1646ea231f4da0b66b37d91e53c23674644e/68747470733a2f2f696d672e736869656c64732e696f2f7061636b61676973742f762f7370617469652f6c61726176656c2d6672616374616c2e7376673f7374796c653d666c61742d737175617265)](https://packagist.org/packages/spatie/laravel-fractal)[![Build Status](https://camo.githubusercontent.com/0584d259761cd11fef583ee2393e962763ba32b0c44d90f5ee6f7b33ed020a6c/68747470733a2f2f7472617669732d63692e6f72672f7370617469652f6c61726176656c2d6672616374616c2e7376673f6272616e63683d6d6173746572)](https://travis-ci.org/spatie/laravel-fractal)[![Quality Score](https://camo.githubusercontent.com/f0a7cbe4dd7e3d7377222a49c9936d71a6880b76aaa67aef0ec5e16f40959807/68747470733a2f2f696d672e736869656c64732e696f2f7363727574696e697a65722f672f7370617469652f6c61726176656c2d6672616374616c2e7376673f7374796c653d666c61742d737175617265)](https://scrutinizer-ci.com/g/spatie/laravel-fractal)[![StyleCI](https://camo.githubusercontent.com/b58466037ca8782280d15ca81f293179c39cbd1197d6d4e63dd64646e3a92735/68747470733a2f2f7374796c6563692e696f2f7265706f732f34333734333133382f736869656c643f6272616e63683d6d6173746572)](https://styleci.io/repos/43743138)[![Total Downloads](https://camo.githubusercontent.com/8516473792aca35daff7d16eea41b9968b9ab4a5bfb65e144082ba32824e9f72/68747470733a2f2f696d672e736869656c64732e696f2f7061636b61676973742f64742f7370617469652f6c61726176656c2d6672616374616c2e7376673f7374796c653d666c61742d737175617265)](https://packagist.org/packages/spatie/laravel-fractal)

The package provides a nice and easy wrapper around [Fractal](http://fractal.thephpleague.com/)for use in your Laravel applications. If you don't know what Fractal does, [take a peek at their intro](http://fractal.thephpleague.com/). 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;

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

$manager = new Manager();

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

$manager->parseIncludes('characters');

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

This package makes that process a tad easier:

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

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

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

There's also a very short syntax available to quickly transform data:

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

You can transform directly from a Laravel collection as well:

```
collect($books)->transformWith(new BookTransformer());
```

Transforming right from a Laravel collection is particularly useful for Eloquent results:

```
Users::all()->transformWith(new UserTransformer())->toArray();
```

Spatie is a webdesign agency based in Antwerp, Belgium. You'll find an overview of all our open source projects [on our website](https://spatie.be/opensource).

Installation in Laravel 5.4
---------------------------

[](#installation-in-laravel-54)

You can pull in the package via composer:

```
composer require spatie/laravel-fractal:^4.0
```

And then follow [the installation instructions of the v4 branch of this package](https://github.com/spatie/laravel-fractal/tree/4.5.0#install).

Installation in Laravel 5.5 and up
----------------------------------

[](#installation-in-laravel-55-and-up)

You can pull in the package via composer:

```
composer require spatie/laravel-fractal
```

The package will automatically register itself.

If you want to [change the default serializer](https://github.com/spatie/fractalistic#changing-the-default-serializer), the [default paginator](https://github.com/spatie/fractalistic#using-pagination), or the default fractal class `Spatie\Fractal\Fractal`you must publish the config file:

```
php artisan vendor:publish --provider="Spatie\Fractal\FractalServiceProvider"
```

> If you're upgrading to Laravel 5.5, the existing config file should be renamed from *laravel-fractal.php* to *fractal.php*

This is the contents of the published file:

```
return [
     /*
     * The default serializer to be used when performing a transformation. It
     * may be left empty to use Fractal's default one. This can either be a
     * string or a League\Fractal\Serializer\SerializerAbstract subclass.
     */
    'default_serializer' => '',

    /* The default paginator to be used when performing a transformation. It
     * may be left empty to use Fractal's default one. This can either be a
     * string or a League\Fractal\Paginator\PaginatorInterface subclass.*/
    'default_paginator' => '',

    /*
     * League\Fractal\Serializer\JsonApiSerializer will use this value to
     * as a prefix for generated links. Set to `null` to disable this.
     */
    'base_url' => null,

    /*
     * If you wish to override or extend the default Spatie\Fractal\Fractal
     * instance provide the name of the class you want to use.
     */
    'fractal_class' => Spatie\Fractal\Fractal::class,

    'auto_includes' => [

        /*
         * If enabled Fractal will automatically add the includes who's
         * names are present in the `include` request parameter.
         */
        'enabled' => true,

        /*
         * The name of key in the request to where we should look for the includes to include.
         */
        'request_key' => 'include',
    ],
```

Usage
-----

[](#usage)

Refer to [the documentation of `spatie/fractalistic`](https://github.com/spatie/fractalistic) to learn all the methods this package provides.

In all code examples you may use `fractal()` instead of `Fractal::create()`.

Send a response with transformed data
-------------------------------------

[](#send-a-response-with-transformed-data)

To return a response with json data you can do this in a Laravel app.

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

return response()->json($books);
```

The `respond()` method on the Fractal class can make this process a bit more streamlined.

```
return fractal($books, new BookTransformer())->respond();
```

You can pass a response code as the first parameter and optionally some headers as the second

```
return fractal($books, new BookTransformer())->respond(403, [
    'a-header' => 'a value',
    'another-header' => 'another value',
]);
```

You can pass json encoding options as the third parameter:

```
return fractal($books, new BookTransformer())->respond(200, [], JSON_PRETTY_PRINT);
```

You can also set the status code and the headers using a callback:

```
use Illuminate\Http\JsonResponse;

return fractal($books, new BookTransformer())->respond(function(JsonResponse $response) {
    $response
        ->setStatusCode(403)
        ->header('a-header', 'a value')
        ->withHeaders([
            'another-header' => 'another value',
            'yet-another-header' => 'yet another value',
        ]);
});
```

Quickly creating a transformer
------------------------------

[](#quickly-creating-a-transformer)

You can run the `make:transformer` command to quickly generate a dummy transformer. By default it will be stored in the `app\Transformers` directory.

Upgrading
---------

[](#upgrading)

From v4 to v5
-------------

[](#from-v4-to-v5)

Rename your config file from `laravel-fractal` to `fractal`

### From v2 to v3

[](#from-v2-to-v3)

`v3` was introduced to swap out the `league/fractal` with `spatie/fractalistic`. Support for Lumen was dropped. You should be able to upgrade a Laravel application from `v2` to `v3` without any code changes.

### From v1 to v2

[](#from-v1-to-v2)

In most cases you can just upgrade to `v2` with making none or only minor changes to your code:

- `resourceName` has been renamed to `withResourceName`.

The main reason why `v2` of this package was tagged is because v0.14 of the underlying [Fractal](http://fractal.thephpleague.com/) by the League contains breaking change. If you use the `League\Fractal\Serializer\JsonApiSerializer` in v2 the `links` key will contain `self`, `first`, `next` and `last`.

Changelog
---------

[](#changelog)

Please see [CHANGELOG](CHANGELOG.md) for more information what has changed recently.

Testing
-------

[](#testing)

```
$ composer test
```

Contributing
------------

[](#contributing)

Please see [CONTRIBUTING](CONTRIBUTING.md) for details.

Security
--------

[](#security)

If you discover any security related issues, please email  instead of using the issue tracker.

Postcardware
------------

[](#postcardware)

You're free to use this package, but if it makes it to your production environment we highly appreciate you sending us a postcard from your hometown, mentioning which of our package(s) you are using.

Our address is: Spatie, Samberstraat 69D, 2060 Antwerp, Belgium.

We publish all received postcards [on our company website](https://spatie.be/en/opensource/postcards).

Credits
-------

[](#credits)

- [Freek Van der Herten](https://twitter.com/freekmurze)
- [All contributors](../../contributors)

Support us
----------

[](#support-us)

Spatie is a webdesign agency based in Antwerp, Belgium. You'll find an overview of all our open source projects [on our website](https://spatie.be/opensource).

Does your business depend on our contributions? Reach out and support us on [Patreon](https://www.patreon.com/spatie). All pledges will be dedicated to allocating workforce on maintenance and new awesome stuff.

License
-------

[](#license)

The MIT License (MIT). Please see [License File](LICENSE.md) for more information.

###  Health Score

31

—

LowBetter than 68% of packages

Maintenance20

Infrequent updates — may be unmaintained

Popularity7

Limited adoption so far

Community19

Small or concentrated contributor base

Maturity71

Established project with proven stability

 Bus Factor1

Top contributor holds 74.4% of commits — single point of failure

How is this calculated?**Maintenance (25%)** — Last commit recency, latest release date, and issue-to-star ratio. Uses a 2-year decay window.

**Popularity (30%)** — Total and monthly downloads, GitHub stars, and forks. Logarithmic scaling prevents top-heavy scores.

**Community (15%)** — Contributors, dependents, forks, watchers, and maintainers. Measures real ecosystem engagement.

**Maturity (30%)** — Project age, version count, PHP version support, and release stability.

###  Release Activity

Cadence

Every ~18 days

Recently: every ~37 days

Total

47

Last Release

3020d ago

Major Versions

0.0.1 → 1.0.02015-10-07

1.9.1 → 2.0.02016-09-27

2.1.0 → 3.0.02016-12-09

3.5.0 → 4.0.02017-04-26

4.5.0 → 5.0.02017-08-30

PHP version history (3 changes)0.0.1PHP &gt;=5.5.0

2.0.0PHP ^5.6|^7.0

5.0.0PHP ^7.0

### Community

Maintainers

![](https://www.gravatar.com/avatar/d2309163519ed0bc5df5b00472f2d9d052d4f6cf207c65bf2885d53b2e6af350?d=identicon)[andrewmclagan](/maintainers/andrewmclagan)

---

Top Contributors

[![freekmurze](https://avatars.githubusercontent.com/u/483853?v=4)](https://github.com/freekmurze "freekmurze (224 commits)")[![sebastiandedeyne](https://avatars.githubusercontent.com/u/1561079?v=4)](https://github.com/sebastiandedeyne "sebastiandedeyne (16 commits)")[![morloderex](https://avatars.githubusercontent.com/u/5677808?v=4)](https://github.com/morloderex "morloderex (14 commits)")[![hosmelq](https://avatars.githubusercontent.com/u/1166143?v=4)](https://github.com/hosmelq "hosmelq (8 commits)")[![DCzajkowski](https://avatars.githubusercontent.com/u/4501047?v=4)](https://github.com/DCzajkowski "DCzajkowski (7 commits)")[![eblount](https://avatars.githubusercontent.com/u/1424719?v=4)](https://github.com/eblount "eblount (3 commits)")[![rupertjeff](https://avatars.githubusercontent.com/u/516384?v=4)](https://github.com/rupertjeff "rupertjeff (2 commits)")[![Maxeee09](https://avatars.githubusercontent.com/u/6651496?v=4)](https://github.com/Maxeee09 "Maxeee09 (2 commits)")[![arubacao](https://avatars.githubusercontent.com/u/7462542?v=4)](https://github.com/arubacao "arubacao (2 commits)")[![ghunti](https://avatars.githubusercontent.com/u/392038?v=4)](https://github.com/ghunti "ghunti (2 commits)")[![miclf](https://avatars.githubusercontent.com/u/3188746?v=4)](https://github.com/miclf "miclf (2 commits)")[![LasseRafn](https://avatars.githubusercontent.com/u/2689341?v=4)](https://github.com/LasseRafn "LasseRafn (1 commits)")[![marcvdm](https://avatars.githubusercontent.com/u/1028066?v=4)](https://github.com/marcvdm "marcvdm (1 commits)")[![okaufmann](https://avatars.githubusercontent.com/u/4414498?v=4)](https://github.com/okaufmann "okaufmann (1 commits)")[![pointercms](https://avatars.githubusercontent.com/u/23186723?v=4)](https://github.com/pointercms "pointercms (1 commits)")[![robinvdvleuten](https://avatars.githubusercontent.com/u/238295?v=4)](https://github.com/robinvdvleuten "robinvdvleuten (1 commits)")[![svenluijten](https://avatars.githubusercontent.com/u/11269635?v=4)](https://github.com/svenluijten "svenluijten (1 commits)")[![vmitchell85](https://avatars.githubusercontent.com/u/1248035?v=4)](https://github.com/vmitchell85 "vmitchell85 (1 commits)")[![andrewmclagan](https://avatars.githubusercontent.com/u/1073259?v=4)](https://github.com/andrewmclagan "andrewmclagan (1 commits)")[![vnarek](https://avatars.githubusercontent.com/u/13958193?v=4)](https://github.com/vnarek "vnarek (1 commits)")

---

Tags

spatieapilaravellumentransformfractallaravel-fractal

###  Code Quality

TestsPHPUnit

### Embed Badge

![Health badge](/badges/andrewmclagan-laravel-fractal/health.svg)

```
[![Health](https://phpackages.com/badges/andrewmclagan-laravel-fractal/health.svg)](https://phpackages.com/packages/andrewmclagan-laravel-fractal)
```

###  Alternatives

[spatie/laravel-fractal

An easy to use Fractal integration for Laravel applications

1.9k15.1M99](/packages/spatie-laravel-fractal)[flugger/laravel-responder

A Laravel Fractal package for building API responses, giving you the power of Fractal and the elegancy of Laravel.

8901.5M5](/packages/flugger-laravel-responder)[spatie/fractalistic

A developer friendly wrapper around Fractal

38715.3M8](/packages/spatie-fractalistic)[andreaselia/laravel-api-to-postman

Generate a Postman collection automatically from your Laravel API

1.0k586.2k3](/packages/andreaselia-laravel-api-to-postman)[mollie/laravel-mollie

Mollie API client wrapper for Laravel &amp; Mollie Connect provider for Laravel Socialite

3624.1M28](/packages/mollie-laravel-mollie)[dragon-code/laravel-json-response

Automatically always return a response in JSON format

1118.6k1](/packages/dragon-code-laravel-json-response)

PHPackages © 2026

[Directory](/)[Categories](/categories)[Trending](/trending)[Changelog](/changelog)[Analyze](/analyze)
