The package provides a nice and easy wrapper around Fractal for use in your Laravel applications. If you don't know what Fractal does, take a peek at their intro. 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.
<img src="https://github-ads.s3.eu-central-1.amazonaws.com/laravel-fractal.jpg?t=1" width="419px" />
We invest a lot of resources into creating best in class open source packages. You can support us by buying one of our paid products.
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. We publish all received postcards on our virtual postcard wall.
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,
the default paginator,
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', ], 'auto_excludes' => [ /* * If enabled Fractal will automatically add the excludes 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 excludes to exclude. */ 'request_key' => 'exclude', ],
Refer to the documentation of spatie/fractalistic to learn all the methods this package provides.
In all code examples you may use fractal() instead of Fractal::create().
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();
You can run the make:transformer command to quickly generate a dummy transformer. By default it will be stored in the app\Transformers directory.
Rename your config file from laravel-fractal to fractal
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.
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 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.
Please see CHANGELOG for more information what has changed recently.
$ composer test
Please see CONTRIBUTING for details.
If you've found a bug regarding security please mail security@spatie.be instead of using the issue tracker.
The MIT License (MIT). Please see License File for more information.


AI赋能电商视觉革命,一站式智能商拍平台
潮际好麦深耕服装行业,是国内AI试衣效果最好的软件。使用先进AIGC能力为电商卖家批量提供优质的、低成本的商拍图。合作品牌有Shein、Lazada、安踏、百丽等65个国内外头部品牌,以及国内10万+淘宝、天猫、京东等主流平台的品牌商家,为卖家节省将近85%的出图成本,提升约3倍出图效率,让品牌能够快速上架。


企业专属的AI法律顾问
iTerms是法大大集团旗下法律子品牌,基于最先进的大语言模型(LLM)、专业的法律知识库和强大的智能体架构,帮助企业扫清合规障碍,筑牢风控防线,成为您企业专属的AI法律顾问。


稳定高效的流量提升解决方案,助力品牌曝光
稳定高效的流量提升解决方案,助力品牌曝光


最新版Sora2模型免费使用,一键生成无水印视频
最新版Sora2模型免费使用,一键生成无水印视频


实时语音翻译/同声传译工具
Transly是一个多场景的AI大语言模型驱动的同声传译、专业翻译助手,它拥有超精准的音频识别翻译能力,几乎零延迟的使用体验和支持多国语言可以让你带它走遍全球,无论你是留学生、商务人士、韩剧美剧爱好者,还是出国游玩、多国会议、跨国追星等等,都可以满足你所有需要同传的场景需求,线上线下通用,扫除语言障碍,让全世界的语言交流不再有国界。


选题、配图、成文,一站式创作,让内容运营更高效
讯飞绘文,一个AI集成平台,支持写作、选题、配图、排版和发布。高效生成适用于各类媒体的定制内容,加速品牌传播,提升内容营销效果。


AI辅助编程,代码自动修复
Trae是一种自适应的集成开发环境(IDE),通过自动化和多元协作改变开发流程。利用Trae,团队能够更快速、精确地编写和部署代码,从而提高编程效率和项目交付速度。Trae具备上下文感知和代码自动完成功能,是提升开发效率的理想工具。


最强AI数据分析助手
小浣熊家族Raccoon,您的AI智能助手,致力于通过先进的人工智能技术,为用户提供高效、便捷的智能服务。无论是日常咨询还是专业问题解答,小浣熊都能以快速、准确的响应满足您的需求,让您的生活更加智能便捷。


像人一样思考的AI智能体
imini 是一款超级AI智能体,能根据人类指令,自主思考、自主完成、并且交付结果的AI智能体。


AI数字人视频创作平台
Keevx 一款开箱即用的AI数字人视频创作平台,广泛适用于电商广告、企业培训与社媒宣传,让全球企业与个人创作者无需拍摄剪辑,就能快速生成多语言、高质量的专业视频。
最新AI工具、AI资讯
独家AI资源、AI项目落地

微信扫一扫关注公众号