To handle a scenario where a product can belong to multiple categories, you should create a pivot table that will store the relationship between products and categories. The pivot table should have two columns: product_id and category_id.
Here's an example migration for the pivot table:
Schema::create('category_product', function (Blueprint $table) {
$table->unsignedBigInteger('category_id');
$table->unsignedBigInteger('product_id');
$table->foreign('category_id')->references('id')->on('categories')->onDelete('cascade');
$table->foreign('product_id')->references('id')->on('products')->onDelete('cascade');
$table->primary(['category_id', 'product_id']);
});
Then, in your Product model, define a many-to-many relationship with Category:
class Product extends Model
{
public function categories()
{
return $this->belongsToMany(Category::class);
}
}
And in your Category model, define the inverse relationship:
class Category extends Model
{
public function products()
{
return $this->belongsToMany(Product::class);
}
}
To retrieve all categories for a product, you can use the categories relationship:
$product = Product::find(1);
$categories = $product->categories;
To add a category to a product, you can use the attach method:
$product = Product::find(1);
$category = Category::find(2);
$product->categories()->attach($category);
And to remove a category from a product, you can use the detach method:
$product = Product::find(1);
$category = Category::find(2);
$product->categories()->detach($category);