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

richard's avatar
Level 21

How to sync data in polymorphic relationship

I have 3 tables in the database.

#statuses
- id
- name

# stageable
- id
- client_file_id
- status_id
-stageable_id
-stageable_type

#modules
- id
- name

The Modules are 'stageable' meaning they can statuses like Not Started, Completed, etc

I have the following code in models

<?php

namespace App;

class Module extends Model
{
    protected $guarded = [];

    public function status()
    {
        return $this->morphToMany(Status::class, 'stageable')->withTimestamps();
    }

}

I want to save the model status.

I have tried


$module->status()->sync(new Status([
    'id' => 2 // e.g status number 2
     'client_file_id' => 1 // Client file ID from request
]));

I get the error from DB that client_file_id cannot be null.

Any idea how to sync the data? I don't want to manually attach and detach them.

0 likes
0 replies

Please or to participate in this conversation.