Laravel 5.4 LengthAwarePaginator

标签 laravel

我的脑子突然在这个问题上崩溃了。任何愿意帮助我的人都非常感谢。

这是 Laravel 5.4 中的 LengthAwarepaginator

这是代码。

$collection = [];

            foreach ($maincategories->merchantCategory as $merchantCat) {

               foreach ($merchantCat->merchantSubcategory as $merchantSub) {

                   foreach($merchantSub->products as $products){

                        $collection[] = $products;
                   }
               }
            }

            $paginate = new LengthAwarePaginator($collection, count($collection), 10, 1, ['path'=>url('api/products')]);

            dd($paginate);

它显示完美,但问题是项目是 100。这是我所有的项目,我正确指定了它。我只需要显示 10。

基于 LengthAwarePaginator 构造函数。这是引用。
public function __construct($items, $total, $perPage, $currentPage = null, array $options = [])

这是屏幕截图。

enter image description here

我哪里做错了?泰

最佳答案

手动创建分页器时,您必须自己对结果集进行切片。分页器的第一个参数应该是所需的结果页面,而不是整个结果集。

来自 pagination documentation :

When manually creating a paginator instance, you should manually "slice" the array of results you pass to the paginator. If you're unsure how to do this, check out the array_slice PHP function.



我建议使用 Collection帮助解决这个问题:
// ...

$collection = collect($collection);

$page = 1;
$perPage = 10;

$paginate = new LengthAwarePaginator(
    $collection->forPage($page, $perPage),
    $collection->count(),
    $perPage,
    $page,
    ['path' => url('api/products')]
);

关于Laravel 5.4 LengthAwarePaginator,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43601095/

相关文章:

Laravel 和 Meteor 密码哈希

php - Laravel - Livewire,如何自定义全局消息URL?

php - 将 api 输出从对象更改为数组 laravel

php - 如何强制 Laravel 对列名使用驼峰命名法

php - 在 Laravel 迁移文件中填充数据库

php - 仅在字符串中合并 Laravel 集合键

php - 为什么存储会返回本地 URL,尽管它已上传到公共(public) S3 存储桶?

javascript - 我在 Laravel5.4 中的 DELETE Ajax 请求上收到 405(方法不允许)错误

laravel - Blade 中的嵌套部分

php - 模型上的 SoftDeletes 会破坏动态属性