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

Fractal Laravel Package

php-open-source-saver/fractal

Fractal is a maintained fork of thephpleague/fractal for transforming complex data into consistent API output. Provides a presentation layer with transformers, type casting, relationship includes, custom serializers, and pagination support for JSON/YAML APIs.

View on GitHub
Deep Wiki
Context7

Technical Evaluation

Architecture Fit

  • Decoupling Layer: Fractal acts as a presentation layer between Laravel Eloquent models and API responses, insulating clients from schema changes. This aligns with API-first and contract-driven development principles.
  • Laravel Synergy: Designed for Laravel’s ecosystem (e.g., IlluminatePaginatorAdapter, IlluminateSimplePaginatorAdapter), reducing friction with existing Laravel APIs.
  • Standard Compliance: Supports JSON:API, HAL, and custom formats, enabling interoperability with modern frontend frameworks (React, Vue) and tools (Postman, Swagger).
  • Nested Data Handling: Solves the "N+1 query problem" via eager loading + embedding (e.g., include=posts.comments), critical for performance in relational APIs.

Integration Feasibility

  • Low-Coupling: Can be incrementally adopted (e.g., start with a single resource/transformer) without rewriting existing API endpoints.
  • Laravel Integration:
    • Works seamlessly with Eloquent models, API resources, and Laravel’s paginator.
    • Supports Lumen (micro-framework) and non-Laravel PHP projects.
  • Transformer Pattern: Encourages separation of concerns (data vs. presentation), improving testability and maintainability.
  • Middleware Hooks: Can integrate with Laravel’s API middleware (e.g., TransformResponse) for automatic serialization.

Technical Risk

Risk Area Mitigation Strategy
Learning Curve Documentation from original thephpleague/fractal is comprehensive; namespace change is trivial.
Performance Overhead Benchmark against raw json_encode for simple APIs; use caching (e.g., Fractal\Cache) for complex responses.
Namespace Migration Automated IDE refactoring (League\FractalPHPOpenSourceSaver\Fractal) reduces manual effort.
Dependency Bloat Lightweight (~1MB); no hard dependencies beyond PHP 8.1.
Long-Term Maintenance Fork is actively maintained (last release: 2026-01-07); MIT license allows forks if needed.

Key Questions for TPM

  1. API Strategy:
    • Is this API public/consumed by third parties? If yes, Fractal’s schema stability is critical.
    • Are you using JSON:API/HAL? If so, leverage JsonApiSerializer for built-in compliance.
  2. Team Expertise:
    • Does the team have experience with transformers/serializers? If not, allocate time for training.
    • Is there buy-in for adopting a new pattern (vs. manual json_encode)?
  3. Existing Codebase:
    • Are responses currently inconsistent or tightly coupled to models?
    • Do you use custom pagination? Fractal supports Laravel’s paginator + Pagerfanta/Doctrine adapters.
  4. Performance:
    • Will this API serve high-throughput requests? Test with large nested datasets.
    • Are you using API caching (e.g., Redis)? Fractal integrates with Fractal\Cache\CacheInterface.
  5. Future-Proofing:
    • Do you plan to add GraphQL later? Fractal’s transformers can be reused in GraphQL resolvers.
    • Will you need multi-format output (JSON/XML)? Fractal supports custom serializers.

Integration Approach

Stack Fit

  • Laravel Ecosystem:
    • Eloquent Models: Transform directly via TransformerAbstract.
    • API Resources: Use Fractal\Resource\Item/Collection alongside Laravel’s ApiResource.
    • Routing: Integrate with Route::middleware('transform') or app()->singleton('fractal', ...).
  • Non-Laravel PHP:
    • Works with any PSR-4 autoloader (Symfony, Slim, etc.).
    • Replace Laravel’s paginator with PhalconFrameworkPaginatorAdapter or DoctrinePaginatorAdapter.
  • Frontend/Tooling:
    • JSON:API: Auto-generates links, meta, and included arrays.
    • GraphQL: Transformers can be adapted for GraphQL PHP (e.g., webonyx/graphql-php).

Migration Path

Phase Action Items Tools/Techniques
Assessment Audit 3–5 API endpoints for nested data and inconsistent schemas. Postman/Newman, PHPStan
Pilot Replace 1–2 endpoints with Fractal transformers. IDE refactoring, composer require
Core Integration Standardize all API responses using Fractal; deprecate raw json_encode. Laravel middleware, app()->bind()
Testing Validate schema stability (e.g., model field rename → no client impact). Pact, Postman collections
Optimization Profile performance; cache frequent responses with Fractal\Cache. Blackfire, Laravel Debugbar

Compatibility

  • Laravel Versions: Tested with Laravel 5+; PHP 8.1+ required.
  • Database: Works with Eloquent, Doctrine, or raw arrays.
  • Pagination: Supports:
    • Laravel’s LengthAwarePaginator, SimplePaginator
    • Pagerfanta, Doctrine, Phalcon, Zend paginators
  • Serialization: JSON:API, HAL, Array, or custom via SerializerInterface.

Sequencing

  1. Start with Simple Resources:
    • Replace return User::all()return fractal->createData(User::all(), new UserTransformer).
  2. Add Relationships:
    • Use include params (e.g., /users?include=posts) for nested data.
  3. Standardize Serialization:
    • Replace json_encode($model->toArray()) with fractal->toArray().
  4. Integrate Pagination:
    • Wrap Laravel paginator: Collection::setPaginator($paginator).
  5. Enforce JSON:API/HAL:
    • Switch to JsonApiSerializer for standardized output.
  6. Automate via Middleware:
    • Add TransformResponse middleware to serialize all API responses.

Operational Impact

Maintenance

  • Pros:
    • Reduced Boilerplate: Eliminates manual foreach loops for relationships.
    • Schema Changes: Decouples API responses from database changes (e.g., rename user_nameusername in DB, but API still returns user_name).
    • Centralized Logic: Transformers live in one place; changes propagate across all API consumers.
  • Cons:
    • Additional Layer: Requires maintaining transformers/serializers alongside models.
    • Debugging Complexity: Nested data issues may require tracing through transformers → managers → serializers.

Support

  • Developer Onboarding:
    • Training Needed: Team must understand transformers, includes, and serializers.
    • Documentation: Leverage original Fractal docs + internal runbooks for common patterns (e.g., "How to add pagination").
  • Client Support:
    • Deprecation Strategy: If breaking API changes are needed, use Fractal’s versioned responses (e.g., Accept: application/vnd.api.v1+json).
    • SDKs: Generate OpenAPI/Swagger specs from Fractal-transformed responses.

Scaling

  • Performance:
    • Caching: Use Fractal\Cache (e.g., Redis) for expensive transformations.
    • Lazy Loading: Load relationships only when include is requested.
    • Benchmark: Compare against raw json_encode for high-throughput APIs.
  • Horizontal Scaling:
    • Stateless transformers work well in queued jobs or serverless (AWS Lambda).
    • Database Load: Eager loading (with()) reduces N+1 queries but may increase initial load time.

Failure Modes

Scenario Mitigation
Transformer Bug Unit test transformers; use Fractal\Test\Mock for isolated testing.
Circular References Configure JsonApiSerializer to handle cycles or use maxDepth.
Pagination Errors Validate paginator adapters (e.g., DoctrinePaginatorAdapter).
Schema Drift Enforce API contracts (e.g., OpenAPI) and use Fractal to shield clients.
PHP 8.1+ Dependency Upgrade PHP or fork the package (MIT license allows modifications).
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.
ilhamsyabani/laravel-volt-starter
thethunderturner/filament-latex
ghostcompiler/laravel-querybuilder
webrek/laravel-telescope-mongodb
anousss007/blatui
zatona-eg/zatona-eg-api
cocosmos/filament-sticky-save-bar
patrickbussmann/oauth2-apple
3brs/enterprise-security-bundle
anousss007/vigilance
supportpal/eloquent-model
ardenexal/fhir-models
laravel-at/laravel-image-sanitize
romalytar/yammi-audit-log-laravel
ardenexal/fhir-validation
arshaviras/weather-widget
laravel-chronicle/core
sunchayn/nimbus
daikazu/eloquent-salesforce-objects
unseen-codes/chat