0
votes

Here's my category model:

public function products() {
    return $this->hasMany('Product');
}

Then i am printing all products that each category has:

@foreach($category->products as $product)
    {{ $product->title }}
@endforeach

However it prints every related product to this category. How can i use pagination in that case? I've tried to print pagination links at the bottom:

<div class="pager">
    {{ $category->products()->paginate(12)->links() }}
</div>

It does print pagination links correctly, but when i change the page - content is not changing.

3

3 Answers

4
votes

Before sending data to view first paginate the result like this.

$products = $category->products()->paginate(12);

now pass this value to the view and just iterate it.

@foreach($products as $product)
    {{$product->title}}
@endforeach

To display links just call links method on the products in the view.

{{$products->links()}}
2
votes

You want to call paginate your products first:

public function products() {
     return $this->hasMany('Product');
}

public function recentProducts() {
     return $this->products()->paginate(12);
}

Then in your view you loop through

@foreach($category->recentProducts() as $product)
     {{ $product->title }}
@endforeach

Then your links

<div class="pager">
    {{ $category->recentProducts()->links() }}
</div>
0
votes

Pass paginated collection to the view:

// controller
$products = $category->products()->paginate(12);

// view
@foreach ($products as $product)

   // do what you need
@endforeach

// links:
$products->links();