Weave Code
Code Weaver
Helps Laravel developers discover, compare, and choose open-source packages. See popularity, security, maintainers, and scores at a glance to make better decisions.
Feedback
Share your thoughts, report bugs, or suggest improvements.
Subject
Message

Laravel Fractal Laravel Package

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.

View on GitHub
Deep Wiki
Context7

Getting Started

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.

Implementation Patterns

  • Fluent API for Complex Transforms: Chain includes, meta, and pagination for rich API responses:
fractal($posts)
    ->transformWith(new PostTransformer())
    ->includeComments()
    ->addMeta(['total' => $posts->count()])
    ->paginate($posts->query()->count())
    ->respond();
  • Collection Macros for Cleaner Eloquent Chains: Leverage the transformWith macro on Eloquent collections:
return Users::with('posts')->get()->transformWith(new UserTransformer())->respond();
  • Auto Includes/Excludes from Request: Enable auto-includes in config/fractal.php, then clients can use ?include=comments,likes&exclude=secret_field. The package automatically parses ?include= and ?exclude= query params.
  • Macro for Reusable Helper Logic: Extend the 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();
  • JSON API Responses: Set 'default_serializer' => JsonApiSerializer::class in config, then control base URLs via base_url for consistent hypermedia links.

Gotchas and Tips

  • Config File Rename on v5 Upgrade: If upgrading from v4, rename laravel-fractal.php to fractal.php—failure causes config defaults to be ignored. Run php artisan config:clear post-upgrade.
  • Null Handling in Includes: Passing null to parseIncludes() or include*() methods throws exceptions. Always validate request parameters first: ->includeComments($request->has('include.comments') ? null : false).
  • Paginator Conflicts: If using custom pagination (e.g., LengthAwarePaginator), explicitly set the default_paginator in config to match your driver (e.g., League\Fractal\Paginator\IlluminatePaginatorAdapter::class).
  • Transformer Resolution Order: The 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(...).
  • Response Callback Gotcha: The respond() callback receives JsonResponse, not Fractal—this is a common source of confusion when trying to chain further fractal methods.
  • Testing Tip: Mock 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.
Weaver

How can I help you explore Laravel packages today?

Conversation history is not saved when not logged in.
Prompt
Add packages to context
No packages found.
davejamesmiller/laravel-breadcrumbs
artisanry/parsedown
christhompsontldr/phpsdk
enqueue/dsn
bunny/bunny
enqueue/test
enqueue/null
enqueue/amqp-tools
milesj/emojibase
bower-asset/punycode
bower-asset/inputmask
bower-asset/jquery
bower-asset/yii2-pjax
laravel/nova
spatie/laravel-mailcoach
spatie/laravel-superseeder
laravel/liferaft
nst/json-test-suite
danielmiessler/sec-lists
jackalope/jackalope-transport