-
Notifications
You must be signed in to change notification settings - Fork 21
Sub Relationship Modifier
Cyvelnet edited this page Feb 13, 2020
·
1 revision
Sub relationship modifier allows simple api resource manipulation on display order and limit the number of records before data response to api call. This feature is optional and you can keep your existing code as it used to be.
<?php
use App\User;
use League\Fractal\TransformerAbstract;
use League\Fractal\ParamBag;
class UserTransformer extends TransformerAbstract
{
/**
* List of resources possible to include.
*
* @var array
*/
protected $availableIncludes = ['orders'];
/**
* List of resources to automatically include.
*
* @var array
*/
protected $defaultIncludes = [];
/**
* Transform object into a generic array.
*
* @var
*
* @return array
*/
public function transform($resource)
{
return [
'id' => $resource['id'],
'name' => $resource['name'],
];
}
/**
* \App\User $user
* \League\Fractal\ParamBag $params
*/
public function includeOrders(User $user, ParamBag $params)
{
list($limit, $offset) = $params->get('limit');
list($$orderColumn, $orderDirection) = $params->get('order');
$orders = $user->orders
->take($limit)
->skip($offset)
->orderBy($orderColumn, $orderDirection);
return $this->collection($orders, new OrderTransformer());
}
}
Finally, call your api /api/v1/users?include=orders:limit(5|1):order(created_at|desc)