Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

ziben69's avatar

Multi level paginator

Hello guys, I have 2 tables categories and products. In category.blade.php I would like to paginate products. In my CategoryController I have:

        $categories = Category::where('visible',1)->orderBy('order', 'asc')->with(['products'=>function($q) use ($id) {
            $q->where('category_id', $id)->where('visible', 1)->orderBy('order', 'asc')->paginate(8);
        }])->get();

in view I have:

@foreach($categories as $category)
@foreach($category->products as $product)
@php
    $productsPaginator = $product->paginate(8);
@endphp
<div class="col-sm-6 col-md-4 col-lg-3 ftco-animate">
    <div class="product">
        <h3><a href="#">{{ $product->title }}</a></h3>
    </div>
</div>
@endforeach
@endforeach
{{ $productsPaginator->links() }}

In DB are 56 products, but each of them have other category_id. It works, but:

{{ $productsPaginator->links() }}

display to me 7 tabs from 1 to 7 - each tabs 8 products. Not quite correctly, it should display as many tabs as there are products in a given category, not as many as there are all. For example, in the category I have 20 products, it should display 3 tabs, not 7. At the moment an error pops up after clicking 4 tabs.

Can someone help? So much thanks.

0 likes
5 replies
Sti3bas's avatar

@ziben69 well, your code is wrong, you don't even using pagination, it should be:

@foreach($categories as $category)
   @php
      $productsPaginator = $category->products()->paginate(8);
   @endphp
   @foreach($productsPaginator as $product)
      <div class="col-sm-6 col-md-4 col-lg-3 ftco-animate">
         <div class="product">
           <h3><a href="#">{{ $product->title }}</a></h3>
         </div>
      </div>
   @endforeach
   {{ $productsPaginator->links() }}
@endforeach
ziben69's avatar

but now it displays my pagination as many times as I have categories in the database.

Sti3bas's avatar

@ziben69 so why you're looping the categories at the top if you only want to show the products of the single category?

Sti3bas's avatar
Sti3bas
Best Answer
Level 53

@ziben69 if you only want to find the single category by its id and then show its products, you should:

Controller:

$category = Category::where('visible', 1)->findOrFail($id);
$products = $category->products()->where('visible', 1)->orderBy('order')->paginate(8);

View:

@foreach($products as $product)
   <div class="col-sm-6 col-md-4 col-lg-3 ftco-animate">
      <div class="product">
        <h3><a href="#">{{ $product->title }}</a></h3>
      </div>
   </div>
@endforeach

{{ $products->links() }}
ziben69's avatar

@sti3bas Thank you. You're right. I got stuck in my code instead of reaching for the simple solution :/

Please or to participate in this conversation.