Skip to content

Instantly share code, notes, and snippets.

@RDelorier
Created January 17, 2017 22:22
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save RDelorier/c9eb467262e5f90c2c3da72498951e0f to your computer and use it in GitHub Desktop.
Save RDelorier/c9eb467262e5f90c2c3da72498951e0f to your computer and use it in GitHub Desktop.
<?php
namespace App\Traits;
use League\Fractal\Pagination\IlluminatePaginatorAdapter;
trait TransformsViaFractal
{
/**
* Convert current item into a fractal instance.
*
* @param array $includes nested relationships to include
*
* @return Spatie\Fractal\Fractal
*/
public function toFractal(array $includes = [])
{
return fractal()
->item($this, $this->newTransformer())
->parseIncludes($includes);
}
/**
* Extends the query builder using macros.
*
* @return Illuminate\Database\Eloquent\Builder
*/
public function newQuery()
{
$query = parent::newQuery();
$instance = new self();
/*
* Paginate the query and wrap the paginator with fractal.
*
* @var null
*/
$query->macro('fractalPagination', function ($builder, ...$parameters) use ($instance) {
$includes = is_array(array_get($parameters, 0)) ? array_shift($parameters) : [];
$paginator = call_user_func_array([$builder, 'paginate'], $parameters);
return fractal()
->collection($paginator->getCollection(), $instance->newTransformer())
->parseIncludes($includes)
->paginateWith(new IlluminatePaginatorAdapter($paginator));
});
return $query;
}
/**
* Extend the model collection with a toFractal method.
*
* @param array $models
*
* @return Spatie\Fractal\Fractal
*/
public function newCollection(array $models = [])
{
$instance = new self();
$collection = parent::newCollection($models);
$collection->macro('toFractal', function ($includes = []) use ($instance) {
return fractal()
->collection($this, $instance->newTransformer())
->parseIncludes($includes);
});
return $collection;
}
/**
* Create a new fractal transformer instance via ioc container.
*
* @return League\Fractal\TransformerAbstract
*/
public function newTransformer()
{
return app('App\\Transformers\\'.class_basename($this).'Transformer');
}
}
@RDelorier
Copy link
Author

Add this to a model and you should be able to use [model|collection]->toFractal() to transform an item or collection.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment