spatie/laravel-fractal
Laravel/Lumen wrapper for League Fractal to transform API data with a fluent, expressive syntax. Supports collections, includes, facades, and helper shortcuts to easily shape Eloquent results into consistent JSON-ready arrays.
Start by installing the package via Composer: composer require spatie/laravel-fractal. No service provider registration is needed—Laravel 5.5+ auto-discovers it. The package immediately exposes a fractal() helper and Fractal facade. For your first use, transform Eloquent data in a controller:
use App\Transformers\UserTransformer;
use App\Models\User;
public function index()
{
return fractal(User::all(), new UserTransformer())->respond();
}
Generate transformers via Artisan: php artisan make:transformer User. Transformers live in app/Transformers and define how models serialize to JSON.
fractal($posts)
->transformWith(new PostTransformer())
->includeComments()
->addMeta(['total' => $posts->count()])
->paginate($posts->query()->count())
->respond();
transformWith macro on Eloquent collections:return Users::with('posts')->get()->transformWith(new UserTransformer())->respond();
config/fractal.php, then clients can use ?include=comments,likes&exclude=secret_field. The package automatically parses ?include= and ?exclude= query params.Fractal class for domain-specific needs:// In a service provider...
Fractal::macro('withUser', fn ($user) => $this->addMeta(['current_user_id' => $user->id]));
// Usage:
fractal($posts)->transformWith(new PostTransformer())->withUser($request->user())->respond();
'default_serializer' => JsonApiSerializer::class in config, then control base URLs via base_url for consistent hypermedia links.laravel-fractal.php to fractal.php—failure causes config defaults to be ignored. Run php artisan config:clear post-upgrade.null to parseIncludes() or include*() methods throws exceptions. Always validate request parameters first: ->includeComments($request->has('include.comments') ? null : false).LengthAwarePaginator), explicitly set the default_paginator in config to match your driver (e.g., League\Fractal\Paginator\IlluminatePaginatorAdapter::class).fractal() helper prioritizes the passed transformer over any resolver. If using transformers with auto-registration, ensure no naming collisions—explicitly pass transformWith() or set via Fractal::create()->transformWith(...).respond() callback receives JsonResponse, not Fractal—this is a common source of confusion when trying to chain further fractal methods.fractal() or use Fractal::spy() in tests to assert on transform calls without rendering full JSON. Check for .toArray() equivalent output using ->getData(true) to bypass JSON encoding.How can I help you explore Laravel packages today?