Before you start giving vote-down or mark as duplicated please read:
I have read Cannot add or update a child row a foreign key constraint fails and it is not my case,
- I have existing record
- my table supports cascade on delete.
- I also have my unsigned columns nullable
-- codes provided below
Issue
I am trying save related data in 3rd table named product_attributes
with sync
method, which gets product_id
and attribute_id
Code
schema
public function up()
{
Schema::create('product_attributes', function (Blueprint $table) {
$table->increments('id');
$table->integer('product_id')->nullable()->unsigned();
$table->integer('attribute_id')->nullable()->unsigned();
});
Schema::table('product_attributes', function (Blueprint $table) {
$table->foreign('product_id')->references('id')->on('products')->onDelete('cascade');
$table->foreign('attribute_id')->references('id')->on('attributes')->onDelete('cascade');
});
}
product model
public function attributes(){
return $this->belongsToMany(Attribute::class, 'product_attributes', 'product_id', 'attribute_id');
}
attribute model
public function products(){
return $this->belongsToMany(Product::class);
}
product controller
$product->save()
$product->attributes()->sync($request->attributes, false);
blade
<select class="form-control" name="attributes[]" id="attributes" multiple="multiple">
@foreach($attributes as $attribute)
<option value="{{ $attribute->id }}">{{ $attribute->title }}</option>
@endforeach
</select>
Error
this is what I'm getting:
SQLSTATE[23000]: Integrity constraint violation: 1452 Cannot add or update a child row: a foreign key constraint fails (`shopping`.`product_attributes`, CONSTRAINT `product_attributes_attribute_id_foreign` FOREIGN KEY (`attribute_id`) REFERENCES `attributes` (`id`) ON DELETE CASCADE) (SQL: insert into `product_attributes` (`attribute_id`, `product_id`) values (*parameters, 3))
Anyone can help with that?
Update
Here is what I get when I send my data to controller