All Projects → spatie → Laravel Fractal

spatie / Laravel Fractal

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

Programming Languages

PHP
23972 projects - #3 most used programming language

Projects that are alternatives of or similar to Laravel Fractal

Laravel Responder
A Laravel Fractal package for building API responses, giving you the power of Fractal with Laravel's elegancy.
Stars: ✭ 673 (-61.5%)
Mutual labels:  api, laravel, lumen, fractal
Lumen Microservice
Lumen on Docker - Skeleton project with Nginx, MySQL & PHP 7 | Aws ECS, Google Kubernates, Azure Container Engine
Stars: ✭ 183 (-89.53%)
Mutual labels:  api, laravel, lumen
Lumen Api Starter
Lumen 8 基础上扩展出的API 启动项目,精心设计的目录结构,规范统一的响应数据格式,Repository 模式架构的最佳实践。
Stars: ✭ 197 (-88.73%)
Mutual labels:  api, lumen, fractal
Restful Api With Laravel Definitive Guide
Repository with the base code for the course "RESTful API with Laravel - Definitive-Guide"
Stars: ✭ 156 (-91.08%)
Mutual labels:  api, laravel, fractal
Jikan Rest
The REST API for Jikan
Stars: ✭ 200 (-88.56%)
Mutual labels:  api, laravel, lumen
Laravel5 Jsonapi
Laravel 5 JSON API Transformer Package
Stars: ✭ 313 (-82.09%)
Mutual labels:  api, laravel, lumen
Rest Api With Lumen
Rest API boilerplate for Lumen micro-framework.
Stars: ✭ 464 (-73.46%)
Mutual labels:  laravel, lumen, fractal
Api Restful Con Laravel Guia Definitiva
Repositorio para el código base del curso "API RESTful con Laravel - Guía Definitiva"
Stars: ✭ 95 (-94.57%)
Mutual labels:  api, laravel, fractal
Laqul
A complete starter kit that allows you create amazing apps that look native thanks to the Quasar Framework. Powered by an API developed in Laravel Framework using the easy GraphQL queries language. And ready to use the Google Firebase features.
Stars: ✭ 110 (-93.71%)
Mutual labels:  api, laravel
Overwatch Api
A RESTful API for the Overwatch Game
Stars: ✭ 112 (-93.59%)
Mutual labels:  api, laravel
Laravel Api Explorer
API explorer for laravel applications
Stars: ✭ 138 (-92.11%)
Mutual labels:  api, laravel
Totoval
An out-of-the-box artisan API web-framework written in go.
Stars: ✭ 110 (-93.71%)
Mutual labels:  api, laravel
Vue Api Query
💎 Elegant and simple way to build requests for REST API
Stars: ✭ 1,528 (-12.59%)
Mutual labels:  api, laravel
Laravel Api Boilerplate
A Boilerplate Project For Laravel API's (NOT MAINTAINED)
Stars: ✭ 113 (-93.54%)
Mutual labels:  api, laravel
Invoice As A Service
💰 Simple invoicing service (REST API): from JSON to PDF
Stars: ✭ 106 (-93.94%)
Mutual labels:  api, laravel
Laravel Hateoas
Expose the authorization logic of your REST API using HATEOAS links
Stars: ✭ 116 (-93.36%)
Mutual labels:  api, laravel
L5 Swagger
OpenApi or Swagger integration to Laravel
Stars: ✭ 1,781 (+1.89%)
Mutual labels:  api, laravel
Taobao Top Client
Taobao top client(SDK) for laravel
Stars: ✭ 105 (-93.99%)
Mutual labels:  laravel, lumen
Vue Lumen Starter
😎 VueJs & Lumen Api Starter.
Stars: ✭ 116 (-93.36%)
Mutual labels:  laravel, lumen
Wizard
Wizard是一款开源的文档管理工具,支持Markdown/Swagger/Table类型的文档。
Stars: ✭ 1,733 (-0.86%)
Mutual labels:  api, laravel

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.

Note that the project description data, including the texts, logos, images, and/or trademarks, for each open source project belongs to its rightful owner. If you wish to add or remove any projects, please contact us at [email protected].