PHPackages                             spatie/fractalistic - 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/fractalistic

ActiveLibrary[API Development](/categories/api)

spatie/fractalistic
===================

A developer friendly wrapper around Fractal

2.11.1(2mo ago)38715.3M—1.5%34[1 PRs](https://github.com/spatie/fractalistic/pulls)8MITPHPPHP ^7.4|^8.0CI passing

Since Dec 9Pushed 2mo ago4 watchersCompare

[ Source](https://github.com/spatie/fractalistic)[ Packagist](https://packagist.org/packages/spatie/fractalistic)[ Docs](https://github.com/spatie/fractalistic)[ GitHub Sponsors](https://github.com/spatie)[ RSS](/packages/spatie-fractalistic/feed)WikiDiscussions main Synced 1mo ago

READMEChangelog (10)Dependencies (4)Versions (30)Used By (8)

A developer friendly wrapper around Fractal
===========================================

[](#a-developer-friendly-wrapper-around-fractal)

[![Latest Version on Packagist](https://camo.githubusercontent.com/b3cda652c06c93054f742ce258de3c58d38c3d8251ec19c0cdb1fd59eaca76b3/68747470733a2f2f696d672e736869656c64732e696f2f7061636b61676973742f762f7370617469652f6672616374616c69737469632e7376673f7374796c653d666c61742d737175617265)](https://packagist.org/packages/spatie/fractalistic)[![Software License](https://camo.githubusercontent.com/55c0218c8f8009f06ad4ddae837ddd05301481fcf0dff8e0ed9dadda8780713e/68747470733a2f2f696d672e736869656c64732e696f2f62616467652f6c6963656e73652d4d49542d627269676874677265656e2e7376673f7374796c653d666c61742d737175617265)](LICENSE.md)[![GitHub Workflow Status](https://camo.githubusercontent.com/d13779f7a4839d8268b0c058e68e188a096f63646c014f607c6c2f55018a2e50/68747470733a2f2f696d672e736869656c64732e696f2f6769746875622f616374696f6e732f776f726b666c6f772f7374617475732f7370617469652f6672616374616c69737469632f72756e2d74657374732e796d6c3f6272616e63683d6d61696e266c6162656c3d7465737473267374796c653d666c61742d737175617265)](https://camo.githubusercontent.com/d13779f7a4839d8268b0c058e68e188a096f63646c014f607c6c2f55018a2e50/68747470733a2f2f696d672e736869656c64732e696f2f6769746875622f616374696f6e732f776f726b666c6f772f7374617475732f7370617469652f6672616374616c69737469632f72756e2d74657374732e796d6c3f6272616e63683d6d61696e266c6162656c3d7465737473267374796c653d666c61742d737175617265)[![Quality Score](https://camo.githubusercontent.com/37b6682454e3d75348b66f40b926950890247aa0fc81e33b2ed41de99a884020/68747470733a2f2f696d672e736869656c64732e696f2f7363727574696e697a65722f672f7370617469652f6672616374616c69737469632e7376673f7374796c653d666c61742d737175617265)](https://scrutinizer-ci.com/g/spatie/fractalistic)[![Total Downloads](https://camo.githubusercontent.com/f4c5531bc52557be89237c7e5c859cfd6704bfb92e9abbc58f0f47c2608b82bd/68747470733a2f2f696d672e736869656c64732e696f2f7061636b61676973742f64742f7370617469652f6672616374616c69737469632e7376673f7374796c653d666c61742d737175617265)](https://packagist.org/packages/spatie/fractalistic)

[Fractal](http://fractal.thephpleague.com/) is an amazing package to transform data before using it in an API. Unfortunately working with Fractal can be a bit verbose.

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 Thrones', '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::create()
   ->collection($books)
   ->transformWith(new BookTransformer())
   ->includeCharacters()
   ->toArray();
```

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

```
Fractal::create($books, new BookTransformer())->toArray();
```

If you want to use this package inside Laravel, it's recommend to use [laravel-fractal](https://github.com/spatie/laravel-fractal) instead. That package contains a few more whistles and bells specifically targetted at Laravel users.

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/c009434e340b38a17bde273e7a92d07c62d5c13fe62ba24d44652ab39a4419c9/68747470733a2f2f6769746875622d6164732e73332e65752d63656e7472616c2d312e616d617a6f6e6177732e636f6d2f6672616374616c69737469632e6a70673f743d31)](https://spatie.be/github-ad-click/fractalistic)

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).

Install
-------

[](#install)

You can pull in the package via composer:

```
composer require spatie/fractalistic
```

Usage
-----

[](#usage)

In the following examples were going to use the following array as example input:

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

But know that any structure that can be looped (for instance a collection) can be used.

Let's start with a simple transformation.

```
Spatie\Fractalistic\Fractal::create()
   ->collection($books)
   ->transformWith(function($book) { return ['id' => $book['id']];})
   ->toArray();
```

This will return:

```
['data' => [['id' => 1], ['id' => 2]]
```

In all following examples it's assumed that you imported the `Spatie\Fractalistic\Fractal` at the top of your php file.

Instead of using a closure you can also pass [a Transformer](http://fractal.thephpleague.com/transformers/):

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

You can also pass the classname of the Transformer:

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

To make your code a bit shorter you could also pass the transform closure, class, or classname as a second parameter of the `collection`-method:

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

Want to get some sweet json output instead of an array? No problem!

```
Fractal::create()->collection($books, new BookTransformer())->toJson();
```

A single item can also be transformed:

```
Fractal::create()->item($books[0], new BookTransformer())->toArray();
```

Using a serializer
------------------

[](#using-a-serializer)

Let's take a look again at the output of the first example:

```
['data' => [['id' => 1], ['id' => 2]];
```

Notice that `data`-key? That's part of Fractal's default behaviour. Take a look at [Fractals's documentation on serializers](http://fractal.thephpleague.com/serializers/) to find out why that happens.

If you want to use another serializer you can specify one with the `serializeWith`-method. The `Spatie\Fractalistic\ArraySerializer` comes out of the box. It removes the `data` namespace for both collections and items.

```
Fractal::create()
   ->collection($books)
   ->transformWith(function($book) { return ['id' => $book['id']];})
   ->serializeWith(new \Spatie\Fractalistic\ArraySerializer())
   ->toArray();

//returns [['id' => 1], ['id' => 2]]
```

You can also pass the serializer classname instead of an instantiation:

```
Fractal::create()
   ->collection($books)
   ->transformWith(BookTransformer::class)
   ->serializeWith(MySerializer::class)
   ->toArray();
```

### Changing the default serializer

[](#changing-the-default-serializer)

You can change the default serializer by providing the classname or an instantiation of your favorite serializer in the config file.

Using includes
--------------

[](#using-includes)

Fractal provides support for [optionally including data](http://fractal.thephpleague.com/transformers/) on the relationships for the data you're exporting. You can use Fractal's `parseIncludes` which accepts a string or an array:

```
Fractal::create()
   ->collection($this->testBooks, new TestTransformer())
   ->parseIncludes(['characters', 'publisher'])
   ->toArray();
```

To improve readablity you can also use a function named `include` followed by the name of the include you want to... include:

```
Fractal::create()
   ->collection($this->testBooks, new TestTransformer())
   ->includeCharacters()
   ->includePublisher()
   ->toArray();
```

Using excludes
--------------

[](#using-excludes)

Similar to includes Fractal also provides support for [optionally excluding data](http://fractal.thephpleague.com/transformers/) on the relationships for the data you're exporting. You can use Fractal's `parseExcludes` which accepts a string or an array:

```
Fractal::create()
   ->collection($this->testBooks, new TestTransformer())
   ->parseExcludes(['characters', 'publisher'])
   ->toArray();
```

To improve readability you can also use a function named `exclude` followed by the name of the include you want to... exclude:

```
Fractal::create()
   ->collection($this->testBooks, new TestTransformer())
   ->excludeCharacters()
   ->excludePublisher()
   ->toArray();
```

Including meta data
-------------------

[](#including-meta-data)

Fractal has support for including meta data. You can use `addMeta` which accepts one or more arrays:

```
Fractal::create()
   ->collection($this->testBooks, function($book) { return ['name' => $book['name']];})
   ->addMeta(['key1' => 'value1'], ['key2' => 'value2'])
   ->toArray();
```

This will return the following array:

```
[
   'data' => [
        ['title' => 'Hogfather'],
        ['title' => 'Game Of Thrones'],
    ],
   'meta' => [
        ['key1' => 'value1'],
        ['key2' => 'value2'],
    ]
];
```

Using pagination
----------------

[](#using-pagination)

Fractal provides a Laravel-specific paginator, `IlluminatePaginatorAdapter`, which accepts an instance of Laravel's `LengthAwarePaginator`and works with paginated Eloquent results. When using some serializers, such as the `JsonApiSerializer`, pagination data can be automatically generated and included in the result set:

```
$paginator = Book::paginate(5);
$books = $paginator->getCollection();

Fractal::create()
    ->collection($books, new TestTransformer())
    ->serializeWith(new JsonApiSerializer())
    ->paginateWith(new IlluminatePaginatorAdapter($paginator))
    ->toArray();
```

Using a cursor
--------------

[](#using-a-cursor)

Fractal provides a simple cursor class, `League\Fractal\Pagination\Cursor`. You can use any other cursor class as long as it implements the `League\Fractal\Pagination\CursorInterface` interface. When using it, the cursor information will be automatically included in the result metadata:

```
$books = $paginator->getCollection();

$currentCursor = 0;
$previousCursor = null;
$count = count($books);
$newCursor = $currentCursor + $count;

Fractal::create()
  ->collection($books, new TestTransformer())
  ->serializeWith(new JsonApiSerializer())
  ->withCursor(new Cursor($currentCursor, $previousCursor, $newCursor, $count))
  ->toArray();
```

Setting a custom resource name
------------------------------

[](#setting-a-custom-resource-name)

Certain serializers wrap the array output with a `data` element. The name of this element can be customized:

```
Fractal::create()
    ->collection($this->testBooks, new TestTransformer())
    ->serializeWith(new ArraySerializer())
    ->withResourceName('books')
    ->toArray();
```

```
Fractal::create()
    ->item($this->testBooks[0], new TestTransformer(), 'book')
    ->serializeWith(new ArraySerializer())
    ->toArray();
```

Limit recursion
---------------

[](#limit-recursion)

To increase or decrease the level of embedded includes you can use `limitRecursion`.

```
Fractal::create()
    ->collection($this->testBooks, new TestTransformer())
    ->includesDataThatHasALotOfRecursion
    ->limitRecursion(5);
```

If you do not call `limitRecursion` a default value of 10 is used.

Quickly transform data with the short function syntax
-----------------------------------------------------

[](#quickly-transform-data-with-the-short-function-syntax)

You can also pass arguments to the `fractal`-function itself. The first arguments should be the data you which to transform. The second one should be a transformer or a `closure` that will be used to transform the data. The third one should be a serializer.

Here are some examples

```
Fractal::create($books, new BookTransformer())->toArray();

Fractal::create($books, new BookTransformer(), new ArraySerializer())->toArray();

Fractal::create($books, BookTransformer::class, ArraySerializer::class)->toArray();

Fractal::create(['item1', 'item2'], function ($item) {
   return $item . '-transformed';
})->toArray();
```

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.

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, Kruikstraat 22, 2018 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)

License
-------

[](#license)

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

###  Health Score

70

—

ExcellentBetter than 100% of packages

Maintenance83

Actively maintained with recent releases

Popularity67

Solid adoption and visibility

Community35

Small or concentrated contributor base

Maturity79

Established project with proven stability

 Bus Factor1

Top contributor holds 58.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 ~124 days

Recently: every ~350 days

Total

28

Last Release

86d ago

Major Versions

0.0.1 → 1.0.02016-12-09

1.0.2 → 2.0.02017-04-26

PHP version history (4 changes)0.0.1PHP ^7.0

1.0.0PHP ^5.6|^7.0

2.9.1PHP ^7.3|^8.0

2.9.2PHP ^7.4|^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 (104 commits)")[![Mohammad-Alavi](https://avatars.githubusercontent.com/u/24431504?v=4)](https://github.com/Mohammad-Alavi "Mohammad-Alavi (13 commits)")[![dependabot[bot]](https://avatars.githubusercontent.com/in/29110?v=4)](https://github.com/dependabot[bot] "dependabot[bot] (12 commits)")[![github-actions[bot]](https://avatars.githubusercontent.com/in/15368?v=4)](https://github.com/github-actions[bot] "github-actions[bot] (10 commits)")[![AdrianMrn](https://avatars.githubusercontent.com/u/12762044?v=4)](https://github.com/AdrianMrn "AdrianMrn (8 commits)")[![sebastiandedeyne](https://avatars.githubusercontent.com/u/1561079?v=4)](https://github.com/sebastiandedeyne "sebastiandedeyne (4 commits)")[![Nielsvanpach](https://avatars.githubusercontent.com/u/10651054?v=4)](https://github.com/Nielsvanpach "Nielsvanpach (4 commits)")[![cviebrock](https://avatars.githubusercontent.com/u/166810?v=4)](https://github.com/cviebrock "cviebrock (2 commits)")[![patinthehat](https://avatars.githubusercontent.com/u/5508707?v=4)](https://github.com/patinthehat "patinthehat (2 commits)")[![AlexVanderbist](https://avatars.githubusercontent.com/u/6287961?v=4)](https://github.com/AlexVanderbist "AlexVanderbist (2 commits)")[![akoepcke](https://avatars.githubusercontent.com/u/5311185?v=4)](https://github.com/akoepcke "akoepcke (2 commits)")[![albertoarena](https://avatars.githubusercontent.com/u/1126630?v=4)](https://github.com/albertoarena "albertoarena (1 commits)")[![JulianBustamante](https://avatars.githubusercontent.com/u/351784?v=4)](https://github.com/JulianBustamante "JulianBustamante (1 commits)")[![lukasvy](https://avatars.githubusercontent.com/u/7466907?v=4)](https://github.com/lukasvy "lukasvy (1 commits)")[![Mahmoudz](https://avatars.githubusercontent.com/u/1983984?v=4)](https://github.com/Mahmoudz "Mahmoudz (1 commits)")[![MannikJ](https://avatars.githubusercontent.com/u/1841856?v=4)](https://github.com/MannikJ "MannikJ (1 commits)")[![oanhnn](https://avatars.githubusercontent.com/u/1757120?v=4)](https://github.com/oanhnn "oanhnn (1 commits)")[![ronnievisser](https://avatars.githubusercontent.com/u/1931199?v=4)](https://github.com/ronnievisser "ronnievisser (1 commits)")[![SupianIDz](https://avatars.githubusercontent.com/u/37969970?v=4)](https://github.com/SupianIDz "SupianIDz (1 commits)")[![antonkomarev](https://avatars.githubusercontent.com/u/1849174?v=4)](https://github.com/antonkomarev "antonkomarev (1 commits)")

---

Tags

apifractaljsonphptransformspatieapitransformfractalfractalistic

###  Code Quality

TestsPest

### Embed Badge

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

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

###  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)[yajra/laravel-datatables-fractal

Laravel DataTables Fractal Plugin.

966.9M29](/packages/yajra-laravel-datatables-fractal)[ellipsesynergie/api-response

Simple package to handle response properly in your API

3751.4M20](/packages/ellipsesynergie-api-response)[cyvelnet/laravel5-fractal

A simple fractal service provider and transformer generator with model attributes for laravel &gt;=5.

79187.2k1](/packages/cyvelnet-laravel5-fractal)

PHPackages © 2026

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