Eloquent model event are saved and created both called when create is used?
In regards to using Eloquent model events, I was wondering how the model events respond to the method calls, if there's any overlap with particular events (common events) and if there are, how to approach writing code for such events?
For example, if I have a model for which I call create()
on, i.e. Model::create($array)
as I understand, behind the scenes, when I call create()
the save()
method is called as shown in the docs:
/**
* Save a new model and return the instance.
*
* @param array $attributes
* @return static
*/
public static function create(array $attributes = [])
{
$model = new static($attributes);
$model->save();
return $model;
}
So keeping this in mind, if I wanted the same behaviour for the saved()
and created()
event, would I simply created an event for the saved()
event and not need to worry about the created()
event as the create()
method is a kind of a wrapper for the save()
method (as shown above). So I could do this:
public static function boot()
{
parent::boot();
// covers created and saved events, as create() method triggers save()
static::saved(function($model) {
// do xyz
});
}
Or would I need to create two separate methods to listen for both events? Like this:
public static function boot()
{
parent::boot();
static::created(function($model) {
// do xyz
});
static::saved(function($model) {
// do xyz
});
}
So just to repeat the questions I stated at the beginning:
- How do model events respond to the method calls
- Is there any overlap with particular events (common events, as described above)
- If there are, how to practically approach writing code for such events
Any guidance on understanding this process would be appreciated, thanks!
Solution 1:
There are 3 events around a Model being saved in the database. These are created
, updated
, and saved
.
created
is called when the model is saved for the first time.
updated
is called when the model is saved any subsequent time.
saved
is called any time the model is saved (including when it's first created).
So saved
is a catch-all.
Additionally, when a model has just been created it has the wasRecentlyCreated
property set to true.
So if you have just a saved
event, you can still handle the difference between a create and an update by checking that property.
As for how you go about handling the code, that's down to you.
Personally, if I had some code that was only needed when the model was created I'd use that method. Similarly for updated.
But if I had some shared code that needed to occur every time the model was saved, but additionally needed something special when it was created, I wouldn't create a separate created
event, I'd just use saved
and check for wasRecentlyCreated
.