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

NoxxieNl's avatar

Save relation and polymorphic relation in one go

Hiya guys :-),

I have three tables:

Erpmails
- id
- name
Erpmail_attachments
- id
- erpmail_id
- attachable_id
- attachable_type
Erpmail_erpdocuments
- id
- name
- description

erpdocuments is an attachable type of attachments.

How can I insert a polymorphic relationship within attachments as the same time I am creating a relation to the erpmails table.

So far I only came up with:

$mail = Erpmail::find(1);

$attachment = new ErpmailAttachment;
$attachment->required = true;
$attachment->required_multiple_cases = false;
$attachment->use_letterhead = true;
$attachment->attachable_id = 1;
$attachment->attachable_type = (new ErpmailErpdocument)->getMorphClass();

$mail->attachments()->save($attachment);

i cant figure out how to attach the attachable model in one go, Any of you guys got a brilliant tip?

Thanks in advance :)

0 likes
1 reply
NoxxieNl's avatar

As soon as I posted this, the light turned on in my head (And some kind of brain fart left my ears..)

$mail = Erpmail::find(1);

$attachment = new ErpmailAttachment;
$attachment->required = true;
$attachment->required_multiple_cases = false;
$attachment->use_letterhead = true;
$attachment->attachable()->associate(ErpmailErpdocument::find(1));

$mail->attachments()->save($attachment);

works like a charm :)

Please or to participate in this conversation.