Reputation: 1992
I am updating my model instance or inserting a new one like this:
$model = Model::updateOrCreate([id' => $request['id']],
$model_to_update_array);
I want to execute some code only when existing model instance ('tourist') was updated (and NOT when a new one was created or nothing changes).
I've read https://laravel.com/docs/5.4/eloquent#events about Eloquent events and it seems to me that I need to use updated or updating event. As I understand these events are 'built-in' in Laravel, so I don't have to use a lot of stuff from here: https://laravel.com/docs/5.4/events
I haven't found a tutorial showing how to implement Eloquent events. Since I am new to events conception at all, it's hard for me to understand how to use them. Can anyone drop a link to a good tutorial about Eloquent events (not events in general, but Eloqeunt events in particular) or maybe it can be shortly explained here?
Thank you in advance!
Upvotes: 0
Views: 405
Reputation: 1992
@TheFallen gave a great answer to this problem in another thread on StackOverflow, please read if you are interested in thoroughly explained solution:
Laravel Eloquent Events - implement to save model if Updated
Upvotes: 0
Reputation: 9749
The easiest way to add Eloquent event for a particular model is to overwrite its boot()
method:
protected static function boot()
{
parent::boot();
static::updating(function ($model) {
});
}
When you put this in your model the anonymous function will run every time when the model is being updated. Please note that there is a difference between calling static::updating()
and static::updated()
depending on when you want to execute your code.
Upvotes: 1