Skip to content

Instantly share code, notes, and snippets.

@nickalcala
Last active July 6, 2019 15:55
Show Gist options
  • Save nickalcala/b5c2684c8cc138af409926b3379fea63 to your computer and use it in GitHub Desktop.
Save nickalcala/b5c2684c8cc138af409926b3379fea63 to your computer and use it in GitHub Desktop.
Laravel/Lumen API Tutorial - Response transformers with PHP League’s Fractal
<?php
namespace App\Http\Controllers;
use Illuminate\Contracts\Pagination\LengthAwarePaginator;
use Illuminate\Http\Request;
use Laravel\Lumen\Routing\Controller as BaseController;
use League\Fractal\Manager;
use League\Fractal\Pagination\IlluminatePaginatorAdapter;
use League\Fractal\Resource\Collection;
use League\Fractal\Resource\Item;
use League\Fractal\Serializer\JsonApiSerializer;
class Controller extends BaseController
{
/**
* @param LengthAwarePaginator $data
* @param $transformer
* @return array
*/
public function paginate($data, $transformer)
{
$manager = $this->getFractalManager();
$resource = new Collection($data, $transformer, $transformer->type);
$resource->setPaginator(new IlluminatePaginatorAdapter($data));
return $manager->createData($resource)->toArray();
}
public function collection($data, $transformer)
{
$manager = $this->getFractalManager();
$resource = new Collection($data, $transformer, $transformer->type);
return $manager->createData($resource)->toArray();
}
public function item($data, $transformer)
{
$manager = $this->getFractalManager();
$resource = new Item($data, $transformer, $transformer->type);
return $manager->createData($resource)->toArray();
}
private function getFractalManager()
{
$request = app(Request::class);
$manager = new Manager();
$manager->setSerializer(new JsonApiSerializer());
if (!empty($request->query('include'))) {
$manager->parseIncludes($request->query('include'));
}
return $manager;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment