ziben69's avatar

Laravel | Displaying products in a particular category

Hello guys, how can I display records from products table (each product have category_id) in category show view?

I have something like that Controller function:

   public function show(CategoryRepository $catRepo, $id)
    {
        $category = $catRepo->find($id);

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

        return view('pages.category.show', [
            'category' => $category,
            'categories' => $categories,
        ]);
    }

$categories query gives me good result but category_id is set to 3. How can I replace this id with the one passed from the view to the controller?

In my view I pass ID like that:

<a href="{{ URL::to('/category/' . $category->id) }}">Example</a>

and inspect gives me result localhost/category/3 so its. After click on button redirects to localhost/category/3. So only how to display products where:

category_id is $category = $catRepo->find($id);

When I try put $category or $id to query an error appears: Undefined variable

0 likes
2 replies
Sinnbeck's avatar
Sinnbeck
Best Answer
Level 102

You can pass a variable to a closure using use

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')->get();
        }])->get();
ziben69's avatar

Oh, in fact, I didn't notice ... Thank you

Please or to participate in this conversation.