Use attach to create relation(s) , sync does ""cleaning" in intermediate table.
https://laravel.com/docs/9.x/eloquent-relationships#attaching-detaching
Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.
I have three models:
In clubOffer Model:
public function coupons(): BelongsToMany
{
return $this->belongsToMany(Coupon::class,'club_offer_coupon_pivot','coupon_id');
}
In coupon Model:
public function clubOffers(): BelongsToMany
{
return $this->belongsToMany(ClubOffer::class, 'club_offer_coupon_pivot','club_offer_id');
}
In clubOfferCouponPivot Model (I suspect the problem is in here):
protected $table = 'club_offer_coupon_pivot';
public function clubOffers()
{
return $this->belongsTo(ClubOffer::class);
}
public function coupon()
{
return $this->belongsTo(Coupon::class);
}
public function coupons()
{
return $this->hasManyThrough(Coupon::class,ClubOffer::class);
}
In my controller, I create a new Coupon model and save it to the database. After that, I want to associate any offers that might exist with it into the pivot table.
When I try to do it from the coupon side of things:
$offers = $clubOffers->where('club_id','=',$cg->id_clubgroup);
foreach ( $offers as $offer ) $coupon->clubOffers()->sync($offer->id);
I get this error:
Field 'coupon_id' doesn't have a default value
insert into club_offer_coupon_pivot (club_offer_id) values (1) where the value 1 is actually the coupon_id
But when I try to do it from the offer side of things, I get the opposite error:
$offers = $clubOffers->where('club_id','=',$cg->id_clubgroup);
foreach ( $offers as $offer ) $offer->coupons()->sync($coupon->id);
Field 'club_offer_id' doesn't have a default value
insert into club_offer_coupon_pivot (coupon_id) values (1213) where the value 1213 is actually the club_offer_id
I have tried all of the following, all come back with varying degrees of failed.
$coupon->clubOffers()->sync($offer->id);
$coupon->clubOffers()->sync($coupon->id,$offers);
$coupon->clubOffers()->sync(['coupon_id'=>$coupon->id],$offers);
and several other variations. Help, please?
Thanks to @sr57 I went back and checked how I'd set up my BelongsToMany relationships. I had failed to specify both keys and in fact provided the wrong one first. So... if you're facing this same problem, here is my resolution.
In the clubOffer Model I added the correct keys in the correct order:
public function coupons(): BelongsToMany
{
return $this->belongsToMany(Coupon::class,'club_offer_coupon_pivot','club_offer_id','coupon_id');
}
In the Coupon Model I added the correct keys in the correct order:
public function clubOffers(): BelongsToMany
{
return $this->belongsToMany(ClubOffer::class, 'club_offer_coupon_pivot','coupon_id','club_offer_id');
}
And in my controller:
foreach ( $offers as $offer )
{
$offer->coupons()->attach(['coupon_id' => $coupon->id], ['club_offer_id' => $offer->id]);
}
Please or to participate in this conversation.