1

I'm using Laravel and I try to use pagination for my products

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

And I get these from a method like this

$this->getAllCategoriesProducts(31)

31 is ID of category

and this is my method :

  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;
    }

but when I use

$this->getAllCategoriesProducts($categroyId)->paginate(8)

it gives me this error

Call to a member function paginate() on array

3
  • Laravel's paginator is integrated with the query builder and Eloquent ORM. Check the document laravel.com/docs/6.x/pagination#introduction Commented Nov 9, 2019 at 9:35
  • Pagination is less valuable if you still get the entire result set per page. If you provide a better description of what data you want from which tables we can help you better. Commented Nov 9, 2019 at 10:03
  • @online Thomas I have multi level category so with above method I get all related categories products and I want to paginate them just this Commented Nov 9, 2019 at 10:15

1 Answer 1

7

You can add paginator manually like this.

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);
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.