Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Laravel change pagination data

Tags:

laravel

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:

Output

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?

like image 748
TheUnreal Avatar asked May 08 '16 17:05

TheUnreal


People also ask

How can we manually create pagination in Laravel?

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/…


1 Answers

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.

like image 172
Murwa Avatar answered Sep 23 '22 13:09

Murwa