php - Laravel relationship pagination
I am trying to paginate the products please refer to the following code:
Here is my show.blade.php
@foreach ($category->products as $product)
<h2>{{ $product->name }}</h2>
@endforeach
Here is my CategoriesController.php
public function show($slug)
{
$category = Category::where('slug', $slug)->firstOrFail();
return view('category.show', compact('category'));
}
Answer
Solution:
You need to paginate the products in the controller method and then pass the paginated result to the view.
public function show($slug)
{
$category = Category::with('products')->where('slug', $slug)->firstOrFail();
$products = $category->products()->paginate(10);
return view('category.show', compact('products'));
}
Then in blade view
@foreach($products as $product)
<h2>{{ $product->name }}</h2>
@endforeach
//To show the pagination links
{!! $products->links() !!}
Source