Skip to content
Advertisement

store data into pivot table laravel 8

i have manytomany relation ship between categroy and product category model

JavaScript

product model

JavaScript

the pivot table

JavaScript

what should i do after this i did not undrestant how attach will work in pivot table and return it with the product as json response ?

edit

this is the schema i am working on enter image description here

i want to give each product it’s own category and this is my product controller store function

JavaScript

Advertisement

Answer

In your product model check your relation.

JavaScript

Also usually the pivot table needs to have only 2 Ids. So in your case only 2 columns: product_id & category_id.

Your table name by convention should be category_product, otherwise, you should specify it on the second parameter on the relationship.

  • Fix this too, you got a typo on update:

    $table->foreignId('attribute_id')->constrained('attributes')->onUpdate('cascade')->onDelete('cascade');

  • And finally to attach:

    $product = Product::find(1);

    $product->categories()->attach($categoryId);

All is explained very well on documentation too: https://laravel.com/docs/8.x/eloquent-relationships

User contributions licensed under: CC BY-SA
6 People found this is helpful
Advertisement