0

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!

Sergej Fomin
  • 1,822
  • 3
  • 24
  • 42

2 Answers2

1

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.

thefallen
  • 9,496
  • 2
  • 34
  • 49
  • Thank you, TheFallen. Where can I read about the difference (updated, updating)? – Sergej Fomin Aug 15 '17 at 11:32
  • @SergejFomin, the documentation doesn't say much about it, but basically `*ing` events are being called before the actual event and `*ed` are called after the event. So in your case if you put your code in `static::updating()` it will run before the actual database update and in `static::updated()` it will run after that. – thefallen Aug 15 '17 at 11:35
  • Hi! So I included protected static function boot().... in my model. How do I use it to check if the model was updated in the Controller? – Sergej Fomin Aug 15 '17 at 14:57
  • @SergejFomin, please post another question with the relevant controller code. – thefallen Aug 15 '17 at 16:11
  • i've posted a new question: https://stackoverflow.com/questions/45698659/laravel-eloquent-events-implement-to-save-model-if-updated – Sergej Fomin Aug 15 '17 at 17:56
0

@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

Sergej Fomin
  • 1,822
  • 3
  • 24
  • 42