Laravel更改分页数据 [英] Laravel change pagination data
问题描述
我的Laravel分页输出就像以前的laravel分页一样,但是我需要更改每个对象的数据数组.我的输出是:
如您所见,数据对象有2个项目,我需要更改.
我的代码是:
$ items = $ this-> items()-> where('position','=',null)-> paginate(15);
哪个返回带有枢轴表的用户项,但是我不喜欢在JSON中显示枢轴表的方式,所以我决定更改项并在项之前使用枢轴来组织每个项.>
为此,我尝试使用 foreach
foreach($ items->数据作为$ item){}
由于我不知道的原因,这给了我一个错误:
未定义的属性:Illuminate \ Pagination \ LengthAwarePaginator :: $ data状态码:500
有帮助吗?
分页者的项目是一个集合.您可以抓取它并转换数据,如下所示:
$ paginator = $ this-> items()-> where('position','=',null)-> paginate(15);$ paginator-> getCollection()-> transform(function($ value){//您的代码在这里返回$ value;});
如果您熟悉 tap
助手,则此代码段的功能完全相同.
$ paginator = tap($ this-> items()-> where('position','=',null)-> paginate(15),function($ paginatedInstance){返回$ paginatedInstance-> getCollection()-> transform(function($ value){返回$ value;});});
我们无法链接方法getCollection 到paginator实例,因为 AbstractPaginator
将返回paginator的基础集合.因此分页程序实例将转换为Collection.因此,请修复此问题,以便我们可以使用点击助手.
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?
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.
这篇关于Laravel更改分页数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!