Description
- Laravel-mongodb Version: ~5.1.0
- PHP Version: 8.1.32
- Database Driver & Version:
ext-mongodb: 1.20.1
mongodb/mongodb: ^1.8 - Laravel version: 10.48.29
Description:
I'm having an issue using this package with models that have a "created" event listener.
I've created a minimal repository with a clean Laravel 10 installation where the error occurs:
🔗 GitHub Repo
I have the following in my model:
static::created(function (MyModelWithCreatedEventNotWorking $model) {
$model->bla = 'bla';
$model->saveQuietly();
});
However, when saving the model, I get the following error:
InvalidArgumentException Cannot update "id" field
This exception is thrown in Builder.php#L742.
Example
This code triggers the error:
$model = new \App\Models\MyModelWithCreatedEventNotWorking();
$model->value = 'value';
$model->save();
// InvalidArgumentException Cannot update "id" field
However, if I call saveQuietly() outside the static::created event, it works as expected:
$model = new \App\Models\MyModelWithoutCreatedEvent();
$model->value = 'value';
$model->bla = 'bla';
$model->saveQuietly();
// Works fine
Workaround
To make it work inside the static::created event, I need to call refresh() before saving:
static::created(function (MyModelWithCreatedEventWorking $model) {
// Fix
$model->refresh();
$model->bla = 'bla';
$model->saveQuietly();
});
Now, the model saves without issues:
$model = new \App\Models\MyModelWithCreatedEventWorking();
$model->value = 'value';
$model->save();
// Works fine
This behavior seems to be a bug because it worked correctly in Laravel 9.* with "jenssegers/mongodb": "^3.9".
Steps to reproduce
- Clone the repo 🔗 GitHub Repo
- Install dependencies
- Run the examples above in
artisan tinker
Expected behaviour
->saveQuietly()
inside the static::created
event should work without needing to call $model->refresh()
.
Actual behaviour
->saveQuietly()
inside the static::created
event only works after calling $model->refresh()
. Without refreshing, it throws the exception:
InvalidArgumentException Cannot update "id" field.
Thanks! 😊