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!