Description
- Laravel-mongodb Version: 4.3.0
- Laravel version: 11.6.0
- PHP Version: 8.2.2
Description:
There seem to be a problem, where using the createOrFirst
builder method, that it does not trigger the creating
or created
model events when the model is being created (not retrieved, as there is no matching model found).
This seems to be caused by the fact that the createOrFirst
method is overwritten in MongoDB package, but it is not calling the $model->save()
method after an attempt to find the model, which would trigger those two events.
This is how it behaved in the past (I just upgraded from v3 to v4) and it is how it behaves in Laravel without MongoDB.
Steps to reproduce
- set up a simple Model class
- call
Model::query()->createOrFirst()
on it - see that it won't trigger the
creating
andcreated
event if it recently created the model (there was no matching model for the attributes)
This will however trigger the retrieving
event instead - even if the model was recently created, but not actually "retrieved"
Expected behaviour
When a model is being created as a new one with use of createOrFirst
method, it should trigger the creating
and created
model events.
Actual behaviour
When a model is being created as a new one with use of createOrFirst
method, there is no creating
nor created
events dispatched.
Workaround
At the moment the only workaround I could think of is to manually try to fetch the model first with use of find/where query, and if its not found, create it with use of Model::query()->create()
method, or $model->save()
- which both will dispatch the creating
and created
events.