Convert Figma logo to code with AI

spatie logolaravel-fractal

An easy to use Fractal wrapper built for Laravel and Lumen applications

1,886
189
1,886
1

Top Related Projects

3,526

Output complex, flexible, AJAX/RESTful data structures.

11,274

🔐 JSON Web Token Authentication for Laravel & Lumen

9,325

A RESTful API package for the Laravel and Lumen frameworks.

Adds CORS (Cross-Origin Resource Sharing) headers support in your Laravel application

Laravel Passport provides OAuth2 server support to Laravel.

Associate users with roles and permissions

Quick Overview

Laravel Fractal is a package that provides an easy way to transform data structures, typically for use in APIs. It integrates the Fractal library with Laravel, allowing developers to create clean, reusable transformers for their data models and collections.

Pros

  • Simplifies the process of transforming complex data structures
  • Integrates seamlessly with Laravel's ecosystem
  • Supports includes (nested relationships) out of the box
  • Allows for easy pagination of transformed data

Cons

  • Adds an additional layer of complexity to simpler projects
  • May have a slight performance overhead for very large datasets
  • Requires learning a new concept (transformers) for developers unfamiliar with Fractal
  • Limited customization options for some advanced use cases

Code Examples

  1. Creating a basic transformer:
use League\Fractal\TransformerAbstract;

class BookTransformer extends TransformerAbstract
{
    public function transform(Book $book)
    {
        return [
            'id' => $book->id,
            'title' => $book->title,
            'author' => $book->author,
        ];
    }
}
  1. Using the transformer in a controller:
use Spatie\Fractal\Fractal;

public function show(Book $book)
{
    return Fractal::create()
        ->item($book, new BookTransformer())
        ->toArray();
}
  1. Transforming a collection with pagination:
public function index()
{
    $books = Book::paginate(10);

    return Fractal::create()
        ->collection($books, new BookTransformer())
        ->paginateWith(new IlluminatePaginatorAdapter($books))
        ->toArray();
}

Getting Started

  1. Install the package via Composer:

    composer require spatie/laravel-fractal
    
  2. Publish the config file (optional):

    php artisan vendor:publish --provider="Spatie\Fractal\FractalServiceProvider"
    
  3. Create a transformer for your model:

    php artisan make:transformer BookTransformer
    
  4. Use the transformer in your controller:

    use Spatie\Fractal\Fractal;
    
    public function show(Book $book)
    {
        return Fractal::create()
            ->item($book, new BookTransformer())
            ->toArray();
    }
    

Competitor Comparisons

3,526

Output complex, flexible, AJAX/RESTful data structures.

Pros of fractal

  • Framework-agnostic, can be used with any PHP project
  • More flexible and customizable for complex data transformations
  • Supports pagination and includes out of the box

Cons of fractal

  • Requires more setup and configuration for Laravel projects
  • Less integration with Laravel-specific features
  • Steeper learning curve for Laravel developers

Code Comparison

fractal:

$resource = new Item($book, new BookTransformer);
$manager = new Manager();
$manager->createData($resource)->toArray();

laravel-fractal:

fractal()
    ->item($book)
    ->transformWith(new BookTransformer)
    ->toArray();

Key Differences

  • laravel-fractal provides a more Laravel-friendly syntax
  • fractal offers more control over the transformation process
  • laravel-fractal integrates seamlessly with Laravel's service container and facades

Use Cases

  • Choose fractal for non-Laravel PHP projects or complex data transformations
  • Opt for laravel-fractal in Laravel applications for easier integration and simpler syntax

Community and Maintenance

  • Both projects are actively maintained and have strong community support
  • fractal has a larger user base due to its framework-agnostic nature
  • laravel-fractal benefits from Spatie's reputation in the Laravel ecosystem
11,274

🔐 JSON Web Token Authentication for Laravel & Lumen

Pros of jwt-auth

  • Specialized for JSON Web Token (JWT) authentication in Laravel
  • Provides robust token management and validation features
  • Offers flexibility in token customization and claims

Cons of jwt-auth

  • Limited to JWT authentication, less versatile for other data transformation needs
  • May require additional setup for complex authentication scenarios
  • Less active maintenance compared to laravel-fractal

Code Comparison

jwt-auth:

$token = JWTAuth::attempt($credentials);
$user = JWTAuth::toUser($token);

laravel-fractal:

$fractal = Fractal::create()->item($user, new UserTransformer());
return response()->json($fractal);

Key Differences

  • Purpose: jwt-auth focuses on JWT authentication, while laravel-fractal is for data transformation and API responses
  • Scope: jwt-auth is specific to authentication, laravel-fractal is more versatile for general API development
  • Integration: jwt-auth requires more setup for authentication flow, laravel-fractal is easier to integrate for data transformation

Use Cases

  • jwt-auth: Best for projects requiring secure, token-based authentication
  • laravel-fractal: Ideal for APIs needing flexible data transformation and presentation

Community and Support

  • jwt-auth: Large user base, but less frequent updates
  • laravel-fractal: Active development, regular updates, and strong community support

Both packages serve different purposes and can be used together in a Laravel project for comprehensive API development and authentication.

9,325

A RESTful API package for the Laravel and Lumen frameworks.

Pros of dingo/api

  • More comprehensive API solution with built-in versioning, rate limiting, and authentication
  • Includes API blueprint generation for documentation
  • Offers more flexibility in terms of response transformations and error handling

Cons of dingo/api

  • Steeper learning curve due to its extensive feature set
  • Less actively maintained compared to laravel-fractal
  • May be overkill for simpler API projects

Code Comparison

dingo/api:

$api = app('Dingo\Api\Routing\Router');

$api->version('v1', function ($api) {
    $api->get('users', 'App\Http\Controllers\UserController@index');
});

laravel-fractal:

use Spatie\Fractal\Facades\Fractal;

return Fractal::create()
    ->collection($users)
    ->transformWith(new UserTransformer())
    ->toArray();

Summary

dingo/api is a more feature-rich solution for building APIs in Laravel, offering versioning, rate limiting, and authentication out of the box. However, it comes with a steeper learning curve and may be excessive for simpler projects. laravel-fractal, on the other hand, focuses specifically on data transformation and serialization, making it easier to integrate into existing projects but lacking some of the advanced features of dingo/api.

Adds CORS (Cross-Origin Resource Sharing) headers support in your Laravel application

Pros of laravel-cors

  • Specifically designed for handling Cross-Origin Resource Sharing (CORS) in Laravel applications
  • Provides easy configuration options for CORS settings
  • Lightweight and focused on a single responsibility

Cons of laravel-cors

  • Limited to CORS functionality, while laravel-fractal offers data transformation capabilities
  • May require additional packages for complex API response handling
  • Less flexibility in terms of data manipulation compared to laravel-fractal

Code Comparison

laravel-cors:

// config/cors.php
return [
    'paths' => ['api/*'],
    'allowed_methods' => ['*'],
    'allowed_origins' => ['*'],
    'allowed_headers' => ['*'],
];

laravel-fractal:

// TransformerController.php
use League\Fractal\Manager;
use League\Fractal\Resource\Item;

$fractal = new Manager();
$resource = new Item($book, new BookTransformer());
return response()->json($fractal->createData($resource)->toArray());

Summary

While laravel-cors excels in handling CORS-related tasks for Laravel applications, laravel-fractal focuses on data transformation and API response structuring. laravel-cors is more lightweight and specific, whereas laravel-fractal offers greater flexibility in manipulating and presenting data. The choice between the two depends on the specific needs of your project, with laravel-cors being ideal for CORS management and laravel-fractal better suited for complex API response handling and data transformation.

Laravel Passport provides OAuth2 server support to Laravel.

Pros of Passport

  • Built-in OAuth2 server implementation for Laravel
  • Seamless integration with Laravel's authentication system
  • Supports first-party and third-party API authentication

Cons of Passport

  • More complex setup and configuration
  • Heavier resource usage due to OAuth2 implementation
  • May be overkill for simple API transformations

Code Comparison

Passport (API token generation):

$user = User::find(1);
$token = $user->createToken('Token Name')->accessToken;

Laravel Fractal (API resource transformation):

$book = Book::find(1);
return fractal()
    ->item($book)
    ->transformWith(new BookTransformer())
    ->toArray();

Key Differences

  • Passport focuses on API authentication and authorization
  • Laravel Fractal specializes in API data transformation and presentation
  • Passport is more suitable for complex API ecosystems with multiple clients
  • Laravel Fractal is ideal for structuring and formatting API responses

Use Cases

Passport:

  • Building OAuth2-based API systems
  • Implementing token-based authentication for mobile apps

Laravel Fractal:

  • Transforming database models into consistent API responses
  • Structuring complex data relationships for API consumption

Both packages serve different purposes in the Laravel ecosystem, with Passport handling authentication and Laravel Fractal focusing on data transformation. The choice between them depends on the specific requirements of your API project.

Associate users with roles and permissions

Pros of laravel-permission

  • Focused on role-based access control, providing a robust permission management system
  • Includes database migrations and models for roles and permissions
  • Offers caching capabilities for improved performance

Cons of laravel-permission

  • Limited to permission management, lacking data transformation features
  • May require additional setup for complex authorization scenarios
  • Does not provide API response formatting capabilities

Code Comparison

laravel-permission:

$user->givePermissionTo('edit articles');
$user->assignRole('writer');
$user->hasPermissionTo('edit articles');

laravel-fractal:

$fractal = new Fractal\Manager();
$resource = new Fractal\Resource\Item($book, new BookTransformer);
$array = $fractal->createData($resource)->toArray();

Summary

laravel-permission is tailored for managing user roles and permissions in Laravel applications, offering a comprehensive solution for access control. On the other hand, laravel-fractal focuses on transforming and presenting data, particularly useful for API responses. While laravel-permission excels in authorization, it lacks the data transformation capabilities provided by laravel-fractal. The choice between the two depends on the specific needs of your project: permission management or data transformation.

Convert Figma logo designs to code with AI

Visual Copilot

Introducing Visual Copilot: A new AI model to turn Figma designs to high quality code using your components.

Try Visual Copilot

README

An easy to use Fractal wrapper built for Laravel and Lumen applications

Latest Version on Packagist run-tests Total Downloads

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.

Support us

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.

Installation in Laravel 5.5 and up

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',
    ],

Usage

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().

Send a response with transformed data

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();

Quickly creating a transformer

You can run the make:transformer command to quickly generate a dummy transformer. By default it will be stored in the app\Transformers directory.

Upgrading

From v4 to v5

Rename your config file from laravel-fractal to fractal

From v2 to v3

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.

From v1 to v2

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.

Changelog

Please see CHANGELOG for more information what has changed recently.

Testing

$ composer test

Contributing

Please see CONTRIBUTING for details.

Security

If you've found a bug regarding security please mail security@spatie.be instead of using the issue tracker.

Credits

License

The MIT License (MIT). Please see License File for more information.