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

Overview

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

Latest Version on Packagist Test Status Code Style Status 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',
    ],

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->appendMeta(['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 discover any security related issues, please email [email protected] instead of using the issue tracker.

Credits

License

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

Comments
  • Upgrade to fractal 0.14.0 and added exclude functionallity at the same time.

    Upgrade to fractal 0.14.0 and added exclude functionallity at the same time.

    So sense no one else made a pr (with working tests) i went ahead and created the exclude functionallity at the same time i updated the fractal package itself.

    • Fix paginator test by just moving out the links array from the meta data.
    • Added exclude functionallity similar to include functionality.
    • upgraded to fractal 0.14.0
    opened by morloderex 7
  • Laravel 8.x Compatibility

    Laravel 8.x Compatibility

    This is an automated pull request from Shift to update your package code and dependencies to be compatible with Laravel 8.x.

    Before merging, you need to:

    • Checkout the l8-compatibility branch
    • Review all comments for additional changes
    • Thoroughly test your package

    If you do find an issue, please report it by commenting on this PR to help improve future automation.

    opened by laravel-shift 6
  • Update package to use Fractal 0.13.0 with JsonApiSerializer changes

    Update package to use Fractal 0.13.0 with JsonApiSerializer changes

    I was trying to use Fractal's JsonApiSerializer with this package, and it wasn't playing nicely with the 1.0 spec. Realized Fractal was updated 3 days ago, so I updated Fractal and the newly failing tests.

    Let me know if I need to change anything or do anything differently to contribute!

    opened by rupertjeff 6
  • Fractal response

    Fractal response

    As per this issue: https://github.com/spatie/fractalistic/issues/7 I am making a PR with proposed changes.

    I am open to suggestions :)


    There may be a benefit in removing the \Spatie\Fractal\Response and using the Illuminate Response instead. We could also try to extend Illuminate Response by Fractal Response to preserve Laravel's native API, yet add our own methods.


    P.S. These have been my first unit tests ever. Please provide some feedback if something is not done 'the right' way. P.P.S. I am indeed terrible at naming things. Currently, public methods are:

    statusCode(); // get a status code
    code();       // set a status code
    getHeaders(); // get all headers
    header();     // set one header
    headers();    // set multiple headers
    

    I would also suggest adding those aliases: (some of them ofc)

    // adding status code
    responseCode();
    withStatusCode();
    withCode();
    addCode();
    setCode();
    setStatusCode();
    
    // adding header/s
    setHeader();
    addHeader();
    withHeader();
    
    setHeaders();
    addHeaders();
    withHeaders();
    
    opened by DCzajkowski 5
  • Improve consistency of config file

    Improve consistency of config file

    This updates the file to make it more consistent with other config files that are built-in with the framework. The comment itself also now features a laravelish Staircase-Like Effect™

    opened by miclf 5
  • auto includes

    auto includes

    This PR implements auto includes feature based on parseIncludes() method from the spatie/fractalistic package:

    • include includes "/books?include=author,publishers.somethingelse"
    • exclude includes "/books?exclude=author,publishers"
    • include parametrs "/books?include=comments:limit(5|1):order(created_at|desc)"

    parseIncludes() and parseExcludes() methods are well tested, no test included.

    opened by chelout 4
  • Backporting auto includes feature to 5.4 target

    Backporting auto includes feature to 5.4 target

    The PR for auto includes only targeted 5.5 branch. This simply backports the same PR to 5.4 target.

    Original PR https://github.com/spatie/laravel-fractal/pull/114/files

    opened by andrewmclagan 3
  • fixes behaviour for passing empty values to parseIncludes

    fixes behaviour for passing empty values to parseIncludes

    I got:

    ErrorException in Fractal.php line 163:
    array_merge(): Argument #2 is not an array
    

    after doing:

    Fractal::collection($data, new $transformerClass, $transformerClass::TYPE)->parseIncludes(Input::get('expand'))->toJson();
    

    I think that this is so common that the method should account for null or anything other than array and string.

    opened by countless-integers 3
  • Update version constraints to allow Laravel 6.0

    Update version constraints to allow Laravel 6.0

    About

    This PR will add ^6.0 to the list of compatible versions of Laravel.

    By preemtively adding the new version, it will allow us to give this fractalistic package a spin, before the final release of Laravel 6.0.

    In the case that you don't feel comfortable merging/tagging this change before the official release, I'll just continue working off of my fork. :relaxed: :v:

    opened by jstoone 2
  • Extend TransformerAbstract class to easily include relations in transformers

    Extend TransformerAbstract class to easily include relations in transformers

    When building up APIs with fractal I found myself repeating the same code to include relations on my Eloquent models:

    // BookTransformer.php
    
    protected $availableIncludes = [
        'author',
        'characters'
    ];
    
    public function includeAuthor(Book $book) {
         return $this->item($book->author, new AuthorTransformer);
    }
    
    public function includeCharacters(Book $book) {
        return $this->collection($book->characters, new CharacterTransformer);
    }
    

    This PR enables you to express the above code more succinctly as:

    // BookTransformer.php
    
    protected $itemIncludes = [
        'author' => AuthorTransformer::class,
    ];
    
    protected $collectionIncludes = [
        'characters' => CharacterTransformer::class,
    ];
    

    Tests and docs included.

    opened by rdarcy1 2
  • Allow specifying the Fractal class to be used (#129)

    Allow specifying the Fractal class to be used (#129)

    As proposed in #129 ;) The default value of fractal_class is Spatie\Fractal\Fractal but if you prefer to have it set to null the code will keep working using the default Spatie\Fractal\Fractal class

    PS: sorry for the horrible commit message

    opened by ghunti 2
Releases(6.0.2)
Owner
Spatie
Webdesign agency based in Antwerp, Belgium
Spatie
An Unleash bundle for Symfony applications to provide an easy way to use feature flags

Unleash Bundle An Unleash bundle for Symfony applications. This provide an easy way to implement feature flags using Gitlab Feature Flags Feature. Ins

Stogon 7 Oct 20, 2022
A RESTful API package for the Laravel and Lumen frameworks.

The Dingo API package is meant to provide you, the developer, with a set of tools to help you easily and quickly build your own API. While the goal of

null 9.3k Jan 7, 2023
Generates OpenApi specification for Laravel, Lumen or Dingo using a configuration array and cebe/php-openapi

OpenApi Generator for Laravel, Lumen and Dingo. About The openapi-gen package provides a convenient way to create OpenApi specifications for Laravel,

Jean Dormehl 5 Jan 25, 2022
Fully unit tested Facebook SDK v5 integration for Laravel & Lumen

Laravel Facebook SDK A fully unit-tested package for easily integrating the Facebook SDK v5 into Laravel and Lumen 5.0, 5.1, 5.2, & 5.3. This is packa

Sammy Kaye Powers 697 Nov 6, 2022
API for Symbiota using the Lumen PHP PHP Micro-Framework By Laravel

symbiota-api API for Symbiota using the Lumen PHP PHP Micro-Framework By Laravel Laravel Lumen Official Documentation Documentation for the Lumen fram

Biodiversity Knowledge Integration Center 2 Jan 3, 2022
A PHP library for the CoinMarketCap API designed to be easy to use.

Help wanted: I don't have enough time to keep updating this library, if you can, don't be shy. Pull requests are welcome. PHP CoinMarketCap API This p

Shahrad Elahi 12 Sep 23, 2022
GraPHPinator ⚡ 🌐 ⚡ Easy-to-use & Fast GraphQL server implementation for PHP

Easy-to-use & Fast GraphQL server implementation for modern PHP. Includes features from latest draft, middleware directives and modules with extra functionality.

Infinityloop.dev 34 Dec 14, 2022
The NKN open API is a blockchain-to-database parser with an easy to use interface written in PHP

The NKN open API is a blockchain-to-database parser with an easy to use interface written in PHP. We're using Laravel as our framework to provide a clean and maintainable code.

Rule110 - The NKN open source community 7 Jun 26, 2022
Raidbots API wrapper which incorporates existing reports and static data into your project.

Raidbots API Raidbots API wrapper which incorporates existing reports and static data into your project. Usage use Logiek\Raidbots\Client; $client =

Logiek 2 Dec 23, 2021
Laravel wrapper for Facebook's GraphQL

Laravel GraphQL Use Facebook's GraphQL with Laravel 6.0+. It is based on the PHP port of GraphQL reference implementation. You can find more informati

Mikk Mihkel Nurges 1.9k Dec 31, 2022
The 1Password Connect PHP SDK provides your PHP applications access to the 1Password Connect API hosted on your infrastructure and leverage the power of 1Password Secrets Automation

1Password Connect PHP SDK The 1Password Connect PHP SDK provides your PHP applications access to the 1Password Connect API hosted on your infrastructu

Michelangelo van Dam 12 Dec 26, 2022
JSON API (jsonapi.org) package for Laravel applications.

cloudcreativity/laravel-json-api Status This package has now been rewritten, substantially improved and released as the laravel-json-api/laravel packa

Cloud Creativity 753 Dec 28, 2022
Zoho CRM API SDK is a wrapper to Zoho CRM APIs. By using this sdk, user can build the application with ease

Archival Notice: This SDK is archived. You can continue to use it, but no new features or support requests will be accepted. For the new version, refe

null 81 Nov 4, 2022
An object oriented PHP wrapper for the Livepeer API

Livepeer PHP An object oriented PHP wrapper for the Livepeer API Requirements PHP >= 7.4 A PSR-17 implementation A PSR-18 implementation Install Via C

Owen Voke 2 Nov 23, 2021
💗 C++ wrapper for Zend API

PHP-X C++ wrapper for Zend API Requirements PHP 7.2 or later Linux/MacOS/Windows GCC 4.8 or later Composer Build phpx (bin) ./build.sh sudo cp bin/php

韩天峰-Rango 815 Dec 6, 2022
A PHP wrapper for the Instagram API. Feedback or bug reports are appreciated.

Instagram PHP API V2 Note: On the 17 Nov 2015 Instagram made changes to their API . Apps created before Nov 17, 2015 wont be affected until Jun 2016.

Christian Metz 1.5k Dec 23, 2022
Class helpers for Symfony applications

Micro-Symfony Tools Class helpers for Symfony applications. Installation composer require yceruto/micro-symfony Micro-Bundle Bundles are a very impor

Yonel Ceruto 4 Sep 23, 2022
A Symfony bundle that provides #StandWithUkraine banner and has some built-in features to block access to your resource for Russian-speaking users.

StandWithUkraineBundle На русском? Смотри README.ru.md This bundle provides a built-in StandWithUkraine banner for your Symfony application and has so

Victor Bocharsky 10 Nov 12, 2022
This project was built to connect WHMCS with GridPane.com's API service so we can create sites within WHMCS.

GridPane Server Module for WHMCS This project was built to connect WHMCS with GridPane.com's API service so we can create sites within WHMCS. Discliam

null 10 Sep 2, 2021