One solution could be to use a many-to-many relationship between the products and categories tables. This way, a product can belong to multiple categories and a category can have multiple products.
To implement this, you can create a pivot table called "category_product" with columns "category_id" and "product_id". Then, in your Product model, define the relationship like this:
public function categories()
{
return $this->belongsToMany(Category::class);
}
And in your Category model:
public function products()
{
return $this->belongsToMany(Product::class);
}
To add a product to a category, you can simply call the attach method on the categories relationship:
$product = Product::find(1);
$category = Category::find(2);
$product->categories()->attach($category);
To retrieve all products in a category, you can use the products relationship on the category:
$category = Category::find(2);
$products = $category->products;
This way, you don't need to traverse the category hierarchy to get all products in a category.