{"id":19324999,"url":"https://github.com/spatie/fractalistic","last_synced_at":"2025-04-14T13:45:17.625Z","repository":{"id":14112617,"uuid":"76027929","full_name":"spatie/fractalistic","owner":"spatie","description":"A framework agnostic, developer friendly wrapper around Fractal","archived":false,"fork":false,"pushed_at":"2024-04-29T13:34:03.000Z","size":125,"stargazers_count":382,"open_issues_count":1,"forks_count":33,"subscribers_count":7,"default_branch":"main","last_synced_at":"2024-05-16T14:43:33.005Z","etag":null,"topics":["api","fractal","json","php","transform"],"latest_commit_sha":null,"homepage":"https://freek.dev/644-a-developer-friendly-wrapper-around-fractal","language":"PHP","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":"mit","status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/spatie.png","metadata":{"files":{"readme":"README.md","changelog":"CHANGELOG.md","contributing":null,"funding":".github/FUNDING.yml","license":"LICENSE.md","code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null,"governance":null,"roadmap":null,"authors":null,"dei":null,"publiccode":null,"codemeta":null},"funding":{"github":"spatie"}},"created_at":"2016-12-09T10:56:28.000Z","updated_at":"2024-06-18T11:05:52.231Z","dependencies_parsed_at":"2024-04-29T14:46:04.794Z","dependency_job_id":"ed773d25-4b2a-4ff1-86db-d8c36078aa02","html_url":"https://github.com/spatie/fractalistic","commit_stats":{"total_commits":126,"total_committers":27,"mean_commits":4.666666666666667,"dds":"0.38888888888888884","last_synced_commit":"09b62d62ced27c6fdb583a90b2d75abef102e8bf"},"previous_names":[],"tags_count":24,"template":false,"template_full_name":null,"repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/spatie%2Ffractalistic","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/spatie%2Ffractalistic/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/spatie%2Ffractalistic/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/spatie%2Ffractalistic/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/spatie","download_url":"https://codeload.github.com/spatie/fractalistic/tar.gz/refs/heads/main","host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":248890460,"owners_count":21178432,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2022-07-04T15:15:14.044Z","host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":["api","fractal","json","php","transform"],"created_at":"2024-11-10T02:08:31.842Z","updated_at":"2025-04-14T13:45:17.593Z","avatar_url":"https://github.com/spatie.png","language":"PHP","funding_links":["https://github.com/sponsors/spatie"],"categories":[],"sub_categories":[],"readme":"# A developer friendly wrapper around Fractal\n\n[![Latest Version on Packagist](https://img.shields.io/packagist/v/spatie/fractalistic.svg?style=flat-square)](https://packagist.org/packages/spatie/fractalistic)\n[![Software License](https://img.shields.io/badge/license-MIT-brightgreen.svg?style=flat-square)](LICENSE.md)\n![GitHub Workflow Status](https://img.shields.io/github/actions/workflow/status/spatie/fractalistic/run-tests.yml?branch=main\u0026label=tests\u0026style=flat-square)\n[![Quality Score](https://img.shields.io/scrutinizer/g/spatie/fractalistic.svg?style=flat-square)](https://scrutinizer-ci.com/g/spatie/fractalistic)\n[![Total Downloads](https://img.shields.io/packagist/dt/spatie/fractalistic.svg?style=flat-square)](https://packagist.org/packages/spatie/fractalistic)\n\n[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.\n\nUsing Fractal data can be transformed like this:\n\n```php\nuse League\\Fractal\\Manager;\nuse League\\Fractal\\Resource\\Collection;\n\n$books = [\n   ['id'=\u003e1, 'title'=\u003e'Hogfather', 'characters' =\u003e [...]], \n   ['id'=\u003e2, 'title'=\u003e'Game Of Thrones', 'characters' =\u003e [...]]\n];\n\n$manager = new Manager();\n\n$resource = new Collection($books, new BookTransformer());\n\n$manager-\u003eparseIncludes('characters');\n\n$manager-\u003ecreateData($resource)-\u003etoArray();\n```\n\nThis package makes that process a tad easier:\n\n```php\nFractal::create()\n   -\u003ecollection($books)\n   -\u003etransformWith(new BookTransformer())\n   -\u003eincludeCharacters()\n   -\u003etoArray();\n```\n\nThere's also a very short syntax available to quickly transform data:\n\n```php\nFractal::create($books, new BookTransformer())-\u003etoArray();\n```\n\nIf 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.\n\n\nSpatie is a webdesign agency based in Antwerp, Belgium. You'll find an overview of all \nour open source projects [on our website](https://spatie.be/opensource).\n\n## Support us\n\n[\u003cimg src=\"https://github-ads.s3.eu-central-1.amazonaws.com/fractalistic.jpg?t=1\" width=\"419px\" /\u003e](https://spatie.be/github-ad-click/fractalistic)\n\nWe 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).\n\nWe 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).\n\n## Install\n\nYou can pull in the package via composer:\n\n``` bash\ncomposer require spatie/fractalistic\n```\n\n## Usage\n\nIn the following examples were going to use the following array as example input:\n\n```php\n$books = [['id'=\u003e1, 'title'=\u003e'Hogfather'], ['id'=\u003e2, 'title'=\u003e'Game Of Kill Everyone']];\n```\n\nBut know that any structure that can be looped (for instance a collection) can be used.\n\nLet's start with a simple transformation.\n\n```php\nSpatie\\Fractalistic\\Fractal::create()\n   -\u003ecollection($books)\n   -\u003etransformWith(function($book) { return ['id' =\u003e $book['id']];})\n   -\u003etoArray();\n``` \n\nThis will return:\n```php\n['data' =\u003e [['id' =\u003e 1], ['id' =\u003e 2]]\n```\n\nIn all following examples it's assumed that you imported the `Spatie\\Fractalistic\\Fractal` at the top of your php file.\n\nInstead of using a closure you can also pass [a Transformer](http://fractal.thephpleague.com/transformers/):\n\n```php\nFractal::create()\n   -\u003ecollection($books)\n   -\u003etransformWith(new BookTransformer())\n   -\u003etoArray();\n```\n\nYou can also pass the classname of the Transformer:\n\n```php\nFractal::create()\n   -\u003ecollection($books)\n   -\u003etransformWith(BookTransformer::class)\n   -\u003etoArray();\n```\n\nTo make your code a bit shorter you could also pass the transform closure, class, or classname as a \nsecond parameter of the `collection`-method:\n\n```php\nFractal::create()-\u003ecollection($books, new BookTransformer())-\u003etoArray();\n```\n\nWant to get some sweet json output instead of an array? No problem!\n```php\nFractal::create()-\u003ecollection($books, new BookTransformer())-\u003etoJson();\n```\n\nA single item can also be transformed:\n```php\nFractal::create()-\u003eitem($books[0], new BookTransformer())-\u003etoArray();\n```\n\n## Using a serializer\n\nLet's take a look again at the output of the first example:\n\n```php\n['data' =\u003e [['id' =\u003e 1], ['id' =\u003e 2]];\n```\n\nNotice that `data`-key? That's part of Fractal's default behaviour. Take a look at\n[Fractals's documentation on serializers](http://fractal.thephpleague.com/serializers/) to find out why that happens.\n\nIf you want to use another serializer you can specify one with the `serializeWith`-method.\nThe `Spatie\\Fractalistic\\ArraySerializer` comes out of the box. It removes the `data` namespace for\nboth collections and items.\n\n```php\nFractal::create()\n   -\u003ecollection($books)\n   -\u003etransformWith(function($book) { return ['id' =\u003e $book['id']];})\n   -\u003eserializeWith(new \\Spatie\\Fractalistic\\ArraySerializer())\n   -\u003etoArray();\n\n//returns [['id' =\u003e 1], ['id' =\u003e 2]]\n```\n\nYou can also pass the serializer classname instead of an instantiation:\n\n```php\nFractal::create()\n   -\u003ecollection($books)\n   -\u003etransformWith(BookTransformer::class)\n   -\u003eserializeWith(MySerializer::class)\n   -\u003etoArray();\n```\n\n### Changing the default serializer\n\nYou can change the default serializer by providing the classname or an instantiation of your favorite serializer in\nthe config file.\n\n## Using includes\n\nFractal provides support for [optionally including data](http://fractal.thephpleague.com/transformers/) on the relationships for\nthe data you're exporting. You can use Fractal's `parseIncludes` which accepts a string or an array:\n\n```php\nFractal::create()\n   -\u003ecollection($this-\u003etestBooks, new TestTransformer())\n   -\u003eparseIncludes(['characters', 'publisher'])\n   -\u003etoArray();\n```\n\nTo improve readablity you can also use a function named `include` followed by the name\nof the include you want to... include:\n\n```php\nFractal::create()\n   -\u003ecollection($this-\u003etestBooks, new TestTransformer())\n   -\u003eincludeCharacters()\n   -\u003eincludePublisher()\n   -\u003etoArray();\n```\n\n## Using excludes\n\nSimilar to includes Fractal also provides support for [optionally excluding data](http://fractal.thephpleague.com/transformers/) on the relationships for\nthe data you're exporting. You can use Fractal's `parseExcludes` which accepts a string or an array:\n\n```php\nFractal::create()\n   -\u003ecollection($this-\u003etestBooks, new TestTransformer())\n   -\u003eparseExcludes(['characters', 'publisher'])\n   -\u003etoArray();\n```\n\nTo improve readability you can also use a function named `exclude` followed by the name\nof the include you want to... exclude:\n\n```php\nFractal::create()\n   -\u003ecollection($this-\u003etestBooks, new TestTransformer())\n   -\u003eexcludeCharacters()\n   -\u003eexcludePublisher()\n   -\u003etoArray();\n```\n\n## Including meta data\n\nFractal has support for including meta data. You can use `addMeta` which accepts \none or more arrays:\n\n```php\nFractal::create()\n   -\u003ecollection($this-\u003etestBooks, function($book) { return ['name' =\u003e $book['name']];})\n   -\u003eaddMeta(['key1' =\u003e 'value1'], ['key2' =\u003e 'value2'])\n   -\u003etoArray();\n```\n\nThis will return the following array:\n\n```php\n[\n   'data' =\u003e [\n        ['title' =\u003e 'Hogfather'],\n        ['title' =\u003e 'Game Of Thrones'],\n    ],\n   'meta' =\u003e [\n        ['key1' =\u003e 'value1'], \n        ['key2' =\u003e 'value2'],\n    ]\n];\n```\n\n## Using pagination\n\nFractal provides a Laravel-specific paginator, `IlluminatePaginatorAdapter`, which accepts an instance of Laravel's `LengthAwarePaginator`\nand works with paginated Eloquent results. When using some serializers, such as the `JsonApiSerializer`, pagination data can be\nautomatically generated and included in the result set:\n\n```php\n$paginator = Book::paginate(5);\n$books = $paginator-\u003egetCollection();\n\nFractal::create()\n    -\u003ecollection($books, new TestTransformer())\n    -\u003eserializeWith(new JsonApiSerializer())\n    -\u003epaginateWith(new IlluminatePaginatorAdapter($paginator))\n    -\u003etoArray();\n```\n\n## Using a cursor\n\nFractal 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:\n\n```php\n$books = $paginator-\u003egetCollection();\n\n$currentCursor = 0;\n$previousCursor = null;\n$count = count($books);\n$newCursor = $currentCursor + $count;\n\nFractal::create()\n  -\u003ecollection($books, new TestTransformer())\n  -\u003eserializeWith(new JsonApiSerializer())\n  -\u003ewithCursor(new Cursor($currentCursor, $previousCursor, $newCursor, $count))\n  -\u003etoArray();\n```\n\n## Setting a custom resource name\n\nCertain serializers wrap the array output with a `data` element. The name of this element can be customized:\n\n```php\nFractal::create()\n    -\u003ecollection($this-\u003etestBooks, new TestTransformer())\n    -\u003eserializeWith(new ArraySerializer())\n    -\u003ewithResourceName('books')\n    -\u003etoArray();\n```\n\n```php\nFractal::create()\n    -\u003eitem($this-\u003etestBooks[0], new TestTransformer(), 'book')\n    -\u003eserializeWith(new ArraySerializer())\n    -\u003etoArray();\n```\n\n## Limit recursion\n\n To increase or decrease the level of embedded includes you can use `limitRecursion`. \n \n ```php\n Fractal::create()\n     -\u003ecollection($this-\u003etestBooks, new TestTransformer())\n     -\u003eincludesDataThatHasALotOfRecursion\n     -\u003elimitRecursion(5);\n ```\n\nIf you do not call `limitRecursion` a default value of 10 is used.\n\n## Quickly transform data with the short function syntax\n\nYou 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.\n\nHere are some examples\n\n```php\nFractal::create($books, new BookTransformer())-\u003etoArray();\n\nFractal::create($books, new BookTransformer(), new ArraySerializer())-\u003etoArray();\n\nFractal::create($books, BookTransformer::class, ArraySerializer::class)-\u003etoArray();\n\nFractal::create(['item1', 'item2'], function ($item) {\n   return $item . '-transformed';\n})-\u003etoArray();\n```\n\n## Changelog\n\nPlease see [CHANGELOG](CHANGELOG.md) for more information what has changed recently.\n\n## Testing\n\n``` bash\n$ composer test\n```\n\n## Contributing\n\nPlease see [CONTRIBUTING](https://github.com/spatie/.github/blob/main/CONTRIBUTING.md) for details.\n\n## Security\n\nIf you've found a bug regarding security please mail [security@spatie.be](mailto:security@spatie.be) instead of using the issue tracker.\n\n## Postcardware\n\nYou'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.\n\nOur address is: Spatie, Kruikstraat 22, 2018 Antwerp, Belgium.\n\nWe publish all received postcards [on our company website](https://spatie.be/en/opensource/postcards).\n\n## Credits\n\n- [Freek Van der Herten](https://twitter.com/freekmurze)\n- [All contributors](../../contributors)\n\n## License\n\nThe MIT License (MIT). Please see [License File](LICENSE.md) for more information.\n","project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fspatie%2Ffractalistic","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Fspatie%2Ffractalistic","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fspatie%2Ffractalistic/lists"}