Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
<?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

This comment has been minimized.

Copy link
Owner Author

@RDelorier RDelorier commented Jan 17, 2017

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