Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

ajsmith_codes's avatar

Attach not working for many-to-many.

    $order->contacts()->attach($contact, ['type' => $request->contact_type]);

It used to work, but not anymore. I get "order_id" doesn't have a default value.

'order_id' is fillable.

Full error:

1364 Field 'order_id' doesn't have a default value (SQL: insert into `salesorder_contacts` (`contact_id`, `type`) values (359, Resolution))"
0 likes
6 replies
ajsmith_codes's avatar

@MohamedTammam Contact is indeed a model. Many Contacts belong to many Salesorders. So, the pivot table is this:

contact_id, order_id, type

MohamedTammam's avatar

@ajsmith_codes I believe the $order and $contact should be saved records in the database, which means they should have the id property.

Are you calling that line after calling save() method ?

ajsmith_codes's avatar

@MohamedTammam Yes, I call that right after saving the Sales order.

EDIT: I also get this error if the contact already exists and I try to attach it to a customer that already exists.

ajsmith_codes's avatar
ajsmith_codes
OP
Best Answer
Level 5

I figured it out. In the model, I had to add the foreign pivot id because the table is named something different.

  public function contacts()
    {
        return $this->belongsToMany('App\Models\Contact\Contact', 'salesorder_contacts', 'contact_id', 'order_id')->withPivot('type');
    }
webrobert's avatar

@ajsmith_codes,

As an aside, the general convention is naming the connecting table alphabetically. ``contacts_salesorders``` Then you won't have to declare it in the relationship.

Please or to participate in this conversation.