spatie/laravel-fractal: API data transformation for Laravel
An easy to use Fractal wrapper built for Laravel and Lumen applications
At a glance
- What is it?
- spatie/laravel-fractal wraps League Fractal for Laravel and Lumen applications, adding concise collection transformation, facade access, response helpers, and configurable request-driven includes. It suits API developers who want explicit transformers without assembling Fractal resources manually.
- Who is it for?
- Adopt spatie/laravel-fractal when a Laravel or Lumen API already uses League Fractal concepts and wants concise transformation and response integration. Do not add it for ordinary internal array formatting where a separate transformer layer would be unnecessary.
- Can I use it commercially?
- Yes. MIT is a permissive licence: you can use, modify and sell software built on it, as long as you keep its copyright and licence notices.
- Is it still maintained?
- Yes. The repository last received commits 1 day ago.
- What is it written in?
- Mainly PHP, according to GitHub's language statistics.
Answers come from the project's GitHub data, last synced on October 23, 2026, and from our analysis. They are not legal advice.
Star history
- spatie/laravel-fractal1,903 ★ · +0
| Repository | 2026-10-16 | 2026-10-23 |
|---|---|---|
| spatie/laravel-fractal | 1.9k | 1.9k |
0 Stars in the last 7 days, measured from the daily GitHub snapshot. Compare with other projects
Editorial analysis
Where laravel-fractal fits in a Laravel API
spatie/laravel-fractal addresses a narrow but common API problem: applying a consistent transformation to records before they leave a Laravel or Lumen application. Raw Eloquent models can expose columns, relationships, or computed fields that do not belong in a public response. League Fractal provides the underlying transformation model, while this package connects it to Laravel conventions and reduces the amount of object assembly required in application code.
The intended audience is PHP developers building API endpoints in Laravel or Lumen. It is most relevant when a response needs named transformers, nested resources, includes, excludes, fieldsets, pagination metadata, or a consistent serializer. The package does not replace controllers, routes, authorization, or Eloquent. It controls the shape of transformed data, so those other layers still determine who may request it and where it comes from.
The README contrasts direct League Fractal setup with a shorter package API. Direct use requires constructing a Manager and a Collection, selecting a transformer, parsing includes, and creating data. The wrapper compresses that sequence into calls such as collection(), transformWith(), includeCharacters(), and toArray(). This is convenience around a real transformation layer, not automatic JSON formatting by itself.
The transformation path from records to serialized data
The documented data flow starts with a PHP array, Laravel collection, or Eloquent result. A BookTransformer or UserTransformer defines how each record is converted. The package sends that source and transformer into Fractal, which produces the transformed structure before the configured serializer represents it.
Three entry styles cover different preferences. The helper function offers a fluent interface. The Fractal facade exposes the same collection workflow to users who prefer facades. The short form combines a source and transformer in one call. The README also documents transformation directly from a Laravel collection, including an Eloquent example using Users::all().
Configuration determines how the resulting Fractal instance behaves. default_serializer can be empty, a serializer name, or a League\Fractal\Serializer\SerializerAbstract subclass. default_paginator follows the same empty-or-instance model, while fractal_class selects the package class used by the integration. The base_url setting controls the prefix used by League\Fractal\Serializer\JsonApiSerializer links and can be set to null.
Request-driven shaping is enabled by default. Names in the include request parameter are added as includes, names in exclude become excludes, and fields controls a fieldset. Each behavior has a separate enabled flag and request_key value. This is useful for public collection endpoints, but it also means the application must validate requested relationship names and fields before allowing them to influence serialization.
Installing the package and publishing Fractal settings
The README documents Composer installation for Laravel 5.5 and up. Composer retrieves the package, after which its service provider registers automatically. No manual provider entry is requested in the documented path.
Run this from the Laravel application that will use the package:
composer require spatie/laravel-fractalThe automatic registration is sufficient for default behavior. Publishing is only necessary when changing the default serializer or paginator, or replacing the default Spatie\Fractal\Fractal class:
php artisan vendor:publish --provider="Spatie\Fractal\FractalServiceProvider"After publication, edit the generated config file as needed. The request-driven defaults shown in the README are enabled for include, exclude, and fields. Applications should retain those defaults only if client input is validated and allowed relationship and field names are known. The README also notes that an existing laravel-fractal.php file should be renamed to fractal.php when upgrading to Laravel 5.5.
A first transformed Laravel response
Given a $books source and a BookTransformer, the shortest documented route calls respond(). The helper transforms the records and returns the serialized response without requiring a separate response()->json() expression.
Use this in a Laravel controller:
return fractal($books, new BookTransformer())->respond();When the endpoint needs explicit control over its HTTP result, respond() accepts a status code, headers, and optional JSON encoding flags. The following returns status 403 with two response headers:
return fractal($books, new BookTransformer())->respond(403, [
'a-header' => 'a value',
'another-header' => 'another value',
]);Passing JSON_PRETTY_PRINT as the third argument changes JSON encoding:
return fractal($books, new BookTransformer())->respond(200, [], JSON_PRETTY_PRINT);The README also documents a callback form that receives an Illuminate\Http\JsonResponse. This supports direct mutation of the response, including status code and header changes. For developers who want to inspect or consume the transformed value inside application code rather than return it immediately, toArray() is the documented terminal operation.
Collections, relationships, and Eloquent results
Collections are the package's clearest use case because each item normally has the same shape and can share one transformer. The fluent form makes the relationship explicit: collection($books) identifies the source type, transformWith(new BookTransformer()) selects the transformation, includeCharacters() adds a related representation, and toArray() returns the result.
fractal()
->collection($books)
->transformWith(new BookTransformer())
->includeCharacters()
->toArray();A facade can replace the helper in that sequence:
Fractal::collection($books)->transformWith(new BookTransformer())->toArray();The README also shows direct transformation from Laravel collections. That path is particularly relevant to Eloquent results because the collection can be obtained through the application's model API before transformation:
Users::all()->transformWith(new UserTransformer())->toArray();The package therefore supports both an explicit Fractal resource workflow and collection-oriented application code. The documentation does not claim that direct collection transformation removes the need for transformer classes. It supplies a concise way to pass existing Laravel collection results into the transformation process.
Limitations, alternatives, and upgrade considerations
The main limitation is conceptual overhead. A service that returns stable, simple arrays may not need Fractal, serializers, request-driven fieldsets, and dedicated transformer classes. Adding this package would introduce another abstraction layer without a corresponding need for reusable response shaping. The package also does not document input validation for include, exclude, or fields. Since those features are enabled by default in the published configuration, request handling remains an application responsibility.
The closest documented alternative is direct League Fractal usage. A developer can instantiate League\Fractal\Manager, create a League\Fractal\Resource\Collection, attach a transformer, call parseIncludes(), and pass the resource to createData(). That approach exposes the underlying Fractal API directly. It suits code that wants explicit Manager configuration and resource construction without the Laravel wrapper. spatie/laravel-fractal is preferable when its helper, facade, Laravel collection integration, response helpers, and default Fractal configuration reduce repeated setup.
Maintenance is supported by the repository's release record. The listed releases include 6.4.0 on 2026-02-21, 6.3.3 on 2025-12-22, and 6.3.2 on 2025-02-14. The repository is not archived, and the last push was on 2026-06-26. The repository includes CHANGELOG.md and UPGRADE.md, which are the relevant files to inspect for version-specific migration work. The MIT license permits use, modification, distribution, and sublicensing under its conditions, subject to inclusion of its copyright and permission notice.
Compatibility must be checked before choosing an upgrade target. The README documents installation for Laravel 5.5 and up, while composer.json is the project-specific file that should define exact dependency constraints. The README excerpt does not state the supported PHP version, minimum Lumen version, every release's breaking changes, or a rollback procedure.
Editorial conclusion
Adopt spatie/laravel-fractal when a Laravel or Lumen API already uses League Fractal concepts and wants concise transformation and response integration. Do not add it for ordinary internal array formatting where a separate transformer layer would be unnecessary. Before adoption, verify compatibility with the Laravel and PHP versions declared in composer.json, inspect the release history and UPGRADE.md for the version you plan to use, and test the configured serializer, paginator, request keys, and response structure against the API contract.
Frequently asked questions
How do I install spatie/laravel-fractal in Laravel?
Run `composer require spatie/laravel-fractal`. The package registers its service provider automatically, while configuration publishing is needed only when changing the serializer, paginator, or default Fractal class.
Can spatie/laravel-fractal transform Eloquent results?
Yes. The README demonstrates `Users::all()->transformWith(new UserTransformer())->toArray()`, as well as transformation through the `fractal()` helper and facade.
How do I return transformed JSON from a Laravel controller?
Use `return fractal($books, new BookTransformer())->respond();`. The method also accepts a response code, headers, JSON encoding options, or an `Illuminate\Http\JsonResponse` callback.
Official sources
Add this badge to your README
If you maintain this project, the badge below links readers to this analysis and shows its maintenance status from the daily GitHub snapshot. Paste the markdown into your README; add ?metric=license or ?metric=stars to the image URL for a different field.
[](https://hysenlabs.com/projects/spatie-laravel-fractal)Star history chart for your README
[](https://hysenlabs.com/projects/spatie-laravel-fractal)Was this useful?