PHPackages                             spatie/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. spatie/laravel-fractal

ActiveLibrary[API Development](/categories/api)

spatie/laravel-fractal
======================

An easy to use Fractal integration for Laravel applications

6.4.0(2mo ago)1.9k15.1M—2.6%187[1 PRs](https://github.com/spatie/laravel-fractal/pulls)20MITPHPPHP ^8.0CI passing

Since Oct 6Pushed 1mo ago27 watchersCompare

[ Source](https://github.com/spatie/laravel-fractal)[ Packagist](https://packagist.org/packages/spatie/laravel-fractal)[ Docs](https://github.com/spatie/laravel-fractal)[ Fund](https://spatie.be/open-source/support-us)[ RSS](/packages/spatie-laravel-fractal/feed)WikiDiscussions main Synced 1mo ago

READMEChangelog (10)Dependencies (8)Versions (75)Used By (20)

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

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

[![Latest Version on Packagist](https://camo.githubusercontent.com/2c8abd7a8dbe9de160541bf2533a1646ea231f4da0b66b37d91e53c23674644e/68747470733a2f2f696d672e736869656c64732e696f2f7061636b61676973742f762f7370617469652f6c61726176656c2d6672616374616c2e7376673f7374796c653d666c61742d737175617265)](https://packagist.org/packages/spatie/laravel-fractal)[![run-tests](https://github.com/spatie/laravel-fractal/actions/workflows/run-tests.yml/badge.svg)](https://github.com/spatie/laravel-fractal/actions/workflows/run-tests.yml)[![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).

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

[](#support-us)

[![](https://camo.githubusercontent.com/b42fe07ed6a38f0e8d93801de9a61932dd8f70b07b40a1ced817739fb32b42d4/68747470733a2f2f6769746875622d6164732e73332e65752d63656e7472616c2d312e616d617a6f6e6177732e636f6d2f6c61726176656c2d6672616374616c2e6a70673f743d31)](https://spatie.be/github-ad-click/laravel-fractal)

We invest a lot of resources into creating [best in class open source packages](https://spatie.be/open-source). You can support us by [buying one of our paid products](https://spatie.be/open-source/support-us).

We highly appreciate you sending us a postcard from your hometown, mentioning which of our package(s) you are using. You'll find our address on [our contact page](https://spatie.be/about-us). We publish all received postcards on [our virtual postcard wall](https://spatie.be/open-source/postcards).

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
     * 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',
    ],

    'auto_excludes' => [

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

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

    'auto_fieldsets' => [

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

        /*
         * The name of key in the request, where we should look for the fieldsets to parse.
         */
        'request_key' => 'fields',
    ],
];
```

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',
        ]);
});
```

You can add methods to the Fractal class using Laravel's Macroable trait. Imagine you want to add some stats to the metadata of your request, you can do so without cluttering your code:

```
use Spatie\Fractal\Fractal;

Fractal::macro('stats', function ($stats) {
    // transform the passed stats as necessary here
    return $this->addMeta(['stats' => $stats]);
});

fractal($books, new BookTransformer())->stats(['runtime' => 100])->respond();
```

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](https://github.com/spatie/.github/blob/main/CONTRIBUTING.md) for details.

Security
--------

[](#security)

If you've found a bug regarding security please mail  instead of using the issue tracker.

Credits
-------

[](#credits)

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

License
-------

[](#license)

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

###  Health Score

76

—

ExcellentBetter than 100% of packages

Maintenance87

Actively maintained with recent releases

Popularity73

Solid adoption and visibility

Community49

Growing community involvement

Maturity83

Battle-tested with a long release history

 Bus Factor1

Top contributor holds 69.9% 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 ~52 days

Recently: every ~109 days

Total

73

Last Release

86d ago

Major Versions

1.9.1 → 2.0.02016-09-27

2.1.0 → 3.0.02016-12-09

3.5.0 → 4.0.02017-04-26

v4.x-dev → 5.0.02017-08-30

5.8.1 → 6.0.02022-01-13

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

2.0.0PHP ^5.6|^7.0

5.0.0PHP ^7.0

5.4.4PHP ^7.1

5.5.0PHP ^7.2

5.8.1PHP ^7.2|^8.0

6.0.0PHP ^8.0

### Community

Maintainers

![](https://avatars.githubusercontent.com/u/7535935?v=4)[Spatie](/maintainers/spatie)[@spatie](https://github.com/spatie)

---

Top Contributors

[![freekmurze](https://avatars.githubusercontent.com/u/483853?v=4)](https://github.com/freekmurze "freekmurze (292 commits)")[![sebastiandedeyne](https://avatars.githubusercontent.com/u/1561079?v=4)](https://github.com/sebastiandedeyne "sebastiandedeyne (16 commits)")[![dependabot[bot]](https://avatars.githubusercontent.com/in/29110?v=4)](https://github.com/dependabot[bot] "dependabot[bot] (14 commits)")[![morloderex](https://avatars.githubusercontent.com/u/5677808?v=4)](https://github.com/morloderex "morloderex (14 commits)")[![github-actions[bot]](https://avatars.githubusercontent.com/in/15368?v=4)](https://github.com/github-actions[bot] "github-actions[bot] (11 commits)")[![AlexVanderbist](https://avatars.githubusercontent.com/u/6287961?v=4)](https://github.com/AlexVanderbist "AlexVanderbist (10 commits)")[![AdrianMrn](https://avatars.githubusercontent.com/u/12762044?v=4)](https://github.com/AdrianMrn "AdrianMrn (8 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)")[![Mohammad-Alavi](https://avatars.githubusercontent.com/u/24431504?v=4)](https://github.com/Mohammad-Alavi "Mohammad-Alavi (4 commits)")[![laravel-shift](https://avatars.githubusercontent.com/u/15991828?v=4)](https://github.com/laravel-shift "laravel-shift (3 commits)")[![eblount](https://avatars.githubusercontent.com/u/1424719?v=4)](https://github.com/eblount "eblount (3 commits)")[![patinthehat](https://avatars.githubusercontent.com/u/5508707?v=4)](https://github.com/patinthehat "patinthehat (3 commits)")[![Maxeee09](https://avatars.githubusercontent.com/u/6651496?v=4)](https://github.com/Maxeee09 "Maxeee09 (2 commits)")[![ghunti](https://avatars.githubusercontent.com/u/392038?v=4)](https://github.com/ghunti "ghunti (2 commits)")[![akoepcke](https://avatars.githubusercontent.com/u/5311185?v=4)](https://github.com/akoepcke "akoepcke (2 commits)")[![MannikJ](https://avatars.githubusercontent.com/u/1841856?v=4)](https://github.com/MannikJ "MannikJ (2 commits)")[![dbohn](https://avatars.githubusercontent.com/u/166164?v=4)](https://github.com/dbohn "dbohn (2 commits)")[![miclf](https://avatars.githubusercontent.com/u/3188746?v=4)](https://github.com/miclf "miclf (2 commits)")[![arubacao](https://avatars.githubusercontent.com/u/7462542?v=4)](https://github.com/arubacao "arubacao (2 commits)")

---

Tags

apifractallaravellumenphptransform-dataspatieapilaravellumentransformfractallaravel-fractal

###  Code Quality

TestsPest

### Embed Badge

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

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

###  Alternatives

[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)[mollie/laravel-mollie

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

3624.1M28](/packages/mollie-laravel-mollie)[specialtactics/l5-api

Dependencies for the Laravel API Boilerplate package

3672.8k2](/packages/specialtactics-l5-api)

PHPackages © 2026

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