Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

WebbieWorks's avatar

Show products based on category id

I am pulling my hair out. I am trying to show products based on category ID's. but it is showing all products.

In my database, I have a categories table (id =1-60), then I have my products table that has category_id which is the id of the category the product belongs to.

Controller

public function categories()
    {
        if (request()->categories) {
            
            $products = Product::with('category_id')->whereHas('category_id', function ($query) {
                $query->where('slug', request()->category_id);
            
            })->get();

            $categories = Category::with('children')->where('parent_id',2)->get();
        
        } else {
            
            $products = Product::all();
            $categories = Category::with('children')->where('parent_id',2)->get();
        }
        return view('used-equipment/category')->with([
            'products' => $products,
            'categories' => $categories,

        ]);

    }

web.php

Route::get('/used-equipment/{category}.php', 'UsedController@categories')->name('usedequipment.categories');

I cannot for the life of me figure out how to show the product based on the category ID.

0 likes
2 replies
wheesnoza's avatar

@webbieworks

I am trying to show products based on category ID's.

Maybe it's because not getting into the first condition. request()->categoriesis a mistake maybe? Isn't request()->catetgory_id?

if (request()->category_id) {
  $products = Product::with('category')->where('category_id', request()->category_id)->get();

Please or to participate in this conversation.