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

panthro's avatar

How to set up a controller that considers product categories?

I have products that can be either be drinks, meat, vegtables or fruit.

I am struggling with how to set this up from a controller point of view.

Would I have a products table and also a category table, then have a category controller that basically got a category with the relationship products (a category has many products).

Or should this be set up differently?

I've considered storing everything on a products table with a type field to denote what type of product it is.

But then I struggle to understand how a controller should work with this, perhaps you would have a product controller, but I would like my urls to look like:

example.com/drinks
example.com/meat
etc.

I'm not sure how that would feed all into the same controller.

Your thoughts are very much appreciated.

0 likes
4 replies
vincent15000's avatar
Level 63

The best approach would be to create a categories table and a products table.

categories : id, name
products : id, name, category_id

Then you define the relationships in the models.

// Category model
public function $products()
{
	return $this->hasMany(Product::class);
}

// Product model
public function $category()
{
	return $this->belongsTo(Category::class);
}

Once this is done, you can these relationships in the controller.

If you already have a category and you want to load all products in that category.

// This could be fine for a URL like https://mydomain.dev/drinks/2/products
// Here 2 is the id of the category for which you want to display the products
$products = $category->products;

If you have a list of products and you want to know the category for each one.

$products = Product::with('category')->get();
panthro's avatar

@vincent15000 thanks, but how can I then make categories appear at the root of my domain...

example.com/drinks
example.com/meat

Would not having the word category or any other word that points to a CategoryController be an issue?

1 like
tykus's avatar

@panthro define a route (at the end of your web.php file) to catch the category wildcard:

Route::get('{category:slug}', [ProductController::class, 'index']);
// ProductController
public function index(Category $category)
{
    $products = $category->products;

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

Please or to participate in this conversation.