ziben69's avatar

Laravel pagination

Hello guys, I have query:

$categories = Category::where('visible',1)->orderBy('order', 'asc')->with(['products'])->paginate(3);;

in my view:

@foreach($categories as $category)
<div class="sidebar-box-2">
    <h2 class="heading mb-4"><a href="#">{{ $category->title }}</a></h2>
    <ul>
    @foreach( $category->products as $product)
        <li><a href="#">{{ $product->title }}</a></li>
    @endforeach
    {{ $category->products->links() }}
    </ul>
</div>
@endforeach

Relationship: Category 1:N Product

How can I paginate products in categories view??

0 likes
1 reply
Sti3bas's avatar
Sti3bas
Best Answer
Level 53

@ziben69 well, you would have to paginate each category individually, so eager loading will not work in this case.

@foreach($categories as $category)
   <!-- ... -->
   @php
      $productsPaginator = $category->products()->paginate(3);
      <!--you also need to set unique page name, otherwise all paginator instances will load the same page -->
      $productsPaginator->setPageName($category->slug . 'Page');
   @endphp
   
   @foreach($productsPaginator as $product)
      <li><a href="#">{{ $product->title }}</a></li>
   @endforeach
   
   {{ $productsPaginator->links() }}
   </ul>
</div>
@endforeach

Please or to participate in this conversation.