elliotk's avatar

Paginate Eager Loaded Relationship

Hello,

I am trying to get pagination working for Products here. Where I have the paginate(6) at the moment, the correct number of Products are returned, although I don't know if it's the correct place to put it.

However, I have tried all sorts to get the links() to show in blade, and I can't figure it out.

Is there a special way with Eager Loaded relations?

class CategoryController extends Controller
{
    public function view(Category $category)
    {
        $category->load(['products' => function ($products) {
            $products->enabled()->with('media')->paginate(6);
        }])->with('media');

        return view('shop.category.index', compact('category'));
    }
}
0 likes
2 replies
Snapey's avatar
Snapey
Best Answer
Level 122

Sorry but you cannot paginate a relation.

You need to return products and category as separate elements.

eg

class CategoryController extends Controller
{
    public function view(Category $category)
    {
        $products = $category->products()->enabled()->with('media')->paginate(6);
      

        return view('shop.category.index', compact('category','products'));
    }
}

Then in the view, iterate over $products and then use

{{ $products->links() }}
1 like

Please or to participate in this conversation.