wintercms / winter

Free, open-source, self-hosted CMS platform based on the Laravel PHP Framework.
https://wintercms.com
MIT License
1.31k stars 188 forks source link

model.relation.beforeAdd and model.relation.afterAdd events not called when using AttachOneOrMany::create() #1147

Open goldmont opened 4 weeks ago

goldmont commented 4 weeks ago

Winter CMS Build

1.2

PHP Version

8.1

Database engine

MySQL/MariaDB

Plugins installed

No response

Issue description

Hi,

I was trying to debug it and, while reading the sources, I saw this and it doesn't feel right at first glance: https://github.com/wintercms/storm/blob/374add95da31e6ba1ab4b07ac6d4f03fa85c2503/src/Database/Relations/Concerns/AttachOneOrMany.php#L153-L155

In my controller, I have something like:

$task->attachments()->create(['data' => $attachment])

However, even if attachments are properly attached to my model, model.relation.beforeAdd and model.relation.afterAdd events are not called because $sessionKey is obviously null.

P.s. From the docs, it reads that is_public property must explicitly set when using the add method. However this condition seems to ensure that the correct value is properly set.

Alternatively, you can prepare a File model before hand, then manually associate the relationship later. Notice the is_public attribute must be set explicitly using this approach.

Any suggestion? Thank you as always.

Steps to replicate

  1. Setup an $attachMany relation.
  2. Attach a file using create method.

Workaround

No response