gergonzalez / lumen-fractal by gergonzalez

League Fractal Wrapper
62
1
2
Package Data
Maintainer Username: gergonzalez
Maintainer Contact: ger@gergonzalez.com (German Gonzalez)
Package Create Date: 2018-04-07
Package Last Update: 2018-04-07
Home Page:
Language: PHP
License: MIT
Last Refreshed: 2025-04-22 03:12:32
Package Statistics
Total Downloads: 62
Monthly Downloads: 0
Daily Downloads: 0
Total Stars: 1
Total Watchers: 2
Total Forks: 0
Total Open Issues: 0

Lumen Fractal wrapper package

This package provides an easy way to use Fractal in Lumen.

Fractal provides a presentation and transformation layer for complex data output, the like found in RESTful APIs.

Getting Started

Prerequisites

  • Lumen <= 5.4
  • Lumen > 5.4 - Not tested yet

Installation

Pull it via composer:

composer require gergonzalez/lumen-fractal

Once installed, register the service provider in your bootstrap/app.php

//Register Service Providers

$app->register(Gergonzalez\Fractal\FractalServiceProvider::class);

Usage

Implement your transformers, add a folder at app/Http/Transformers and put them there.

For example, UserTransformer.php:


namespace App\Http\Transformers;

use League\Fractal\TransformerAbstract;
use App\User;

class UserTransformer extends TransformerAbstract
{
    protected $availableIncludes = [
    ];

    protected $defaultIncludes = [
    ];

    /**
     * Turn User object into a generic array.
     *
     * @return array
     */
    public function transform(User $user)
    {
        return [
            'id' => $user->id,
            'email' => $user->email,
        ];
    }
}


And then, at your controller, if you retrieve only one item:


	use App\Http\Transformers\UserTransformer;

	class UserController extends Controller
	{

	    public function show(Request $request, $userId)
	    {
	        $user = User::findOrFail($userId);

	        return response()->json(app('fractal')->item($user, new UserTransformer())->getArray());
	    }

	}

Or a collection:


	use App\Http\Transformers\UserTransformer;

	class UserController extends Controller
	{

	    public function index(Request $request)
	    {
	        return response()->json(app('fractal')->collection(User::all(), new UserTransformer())->getArray());
	    }
	}

You can also use includes, defaults, etc. WIP docs.

If you need a real example of use, you can check here

License

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