amitdev's avatar

One Product -> Multiple Categories

One Product -> Multiple Categories

In product table categories are stored in like "2,3,4" , these are categories id

when it is one product -> one category hasMany / belongsTo is working

But not with multiple categories , how this can be done eloquent query

0 likes
2 replies
LaryAI's avatar
Level 58

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);
amitdev's avatar

belongsToMany relation is not working tried this option as well

Please or to participate in this conversation.