My Laravel pagination output is like laravel pagination used to be, but I need to change the data array for each object. My output is:
As you can see, the data object has 2 items, which I need to change.
My code is:
$items = $this->items() ->where('position', '=', null) ->paginate(15);
Which returns the user items with pivot table, but I don't like the way the pivot table is shown in the JSON, so I decided to change the items and organize each item with the pivot before the item.
For this purpose, I tried to use foreach
foreach ($items->data as $item) { }
which giving my an error, for a reason I don't know:
Undefined property: Illuminate\Pagination\LengthAwarePaginator::$data" status_code: 500
Any help?
Just to say (Laravel doc): When manually creating a paginator instance, you should manually "slice" the array of results you pass to the paginator. Could you explain parameters please? The parameters are discussed over the construct method: laravel.com/api/5.0/Illuminate/Pagination/…
The paginator's items is a collection. You can grab it and transform the data like so:
$paginator = $this->items()->where('position', '=', null)->paginate(15); $paginator->getCollection()->transform(function ($value) { // Your code here return $value; });
If you are familiar with tap
helper here is the snippet that does exact same.
$paginator = tap($this->items()->where('position', '=', null)->paginate(15),function($paginatedInstance){ return $paginatedInstance->getCollection()->transform(function ($value) { return $value; }); });
We can't chain method getCollection to paginator instance because AbstractPaginator
will return paginator's underlying collection. so the paginator instance will be transformed to Collection. So fix that we can use tap helper.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With