Created
January 17, 2017 22:22
-
-
Save RDelorier/c9eb467262e5f90c2c3da72498951e0f to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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'); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this to a model and you should be able to use
[model|collection]->toFractal()
to transform an item or collection.