在数组laravel上分页

时间:2019-11-09 09:13:51

标签: php laravel

我正在使用Laravel,并且尝试对产品使用分页

        private string GetUniqueName(string fileName)
    {
        fileName = Path.GetFileName(fileName);
        return Path.GetFileNameWithoutExtension(fileName)
               + "_" + Guid.NewGuid().ToString().Substring(0, 4)
               + Path.GetExtension(fileName);
    }

我是从这样的方法中得到的

array:4 [▼
  0 => Product {#770 ▶}
  1 => Product {#766 ▶}
  2 => Product {#814 ▶}
  3 => Product {#846 ▶}
]

31是类别的ID

这是我的方法:

$this->getAllCategoriesProducts(31)

但是当我使用

  public function getAllCategoriesProducts($cat_id){
      $allProducts = [];
      foreach(ProductCategory::find($cat_id)->children()->get() as $subCategory){
        if($subCategory->children()->exists()){
          foreach($subCategory->children()->get() as $subSubCategory){
            foreach($subSubCategory->products()->get() as $product){
            $allProducts[] = $product;
            }
          }
          if($subSubCategory->children()->exists()){
            foreach($subSubCategory->children()->get() as $subSubSubCategory){
              foreach($subSubSubCategory->products()->get() as $product){
              $allProducts[] = $product;
              }
              if($subSubSubCategory->children()->exists()){
                foreach($subSubSubCategory->children()->get() as $subSubSubSubCategory){
                  foreach($subSubSubSubCategory->products()->get() as $product){
                  $allProducts[] = $product;
                  }
                }
              }
            }
          }
        }
      }
      return $allProducts;
    }

它给我这个错误

  

在数组上调用成员函数paginate()

1 个答案:

答案 0 :(得分:3)

您可以像这样手动添加分页器。

use Illuminate\Pagination\LengthAwarePaginator;

$products = $this->getAllCategoriesProducts(31);
$total = count($products);
$perPage = 5; // How many items do you want to display.
$currentPage = 1; // The index page.
$paginator = new LengthAwarePaginator($products, $total, $perPage, $currentPage);