Laravel 5: Eloquent Events

Eloquent Events


Eloquent models fire several events, allowing you to hook into various points in the model’s lifecycle.

note:
I am talking about Eloquent events here.
Laravel allows to create and register also other, custom events.
Procedure is slightly different, since Eloquent events are native and you do not have to create them, map them and register them.
More about general events: here.

This functionality is like jQuery events, if you are familiar with jQuery.

Lets see something like click event:

When you click on button, alert with message ‘You clicked me!’ pops up on the screen.

Same happens when Eloquent event fires.
Even function you use to register such even looks somewhat similar:

But, lets do this by the numbers, to avoid confusion.

 


Eloquent already provides you with some builtin events, so no need to create them and map them

What events are at your disposal:

  • creating, created (this auto triggers saving, saved),
  • updating, updated (this auto triggers saving, saved),
  • saving, saved,
  • deleting, deleted,
  • restoring, restored

I think there is no reason to explain, what actual DB action these events are triggered by.

 


To let Laravel know about your intention to use Eloquent events, you have to register them.

Depending, on what you want to accomplish, you may use Laravel native provider class:

… or create your own.

I would opt for creating a separate class and even try to group them in sub-folders inside of:

Reasons:

  • AppServiceProvider can get very crowded very fast
  • it is not a very good approach to get maintainable and future proof code

Unless you are using observer class.
More about it: here.

 


Lets create provider.

Bets and fastest way is to use Laravel CLI utility: Artisan.

Above code created for me MyTesterProvider, which looks like this:

 


Lets register provider.

We have MyTesterProvider provider ready, but Laravel does not know yet about it.
Lets be nice and inform Laravel, that we have just created a new service provider.

Lets open this file:

… and find:

Somewhere on the bottom of ‘providers’, lets add this:

Now, Laravel knows, that it has another service provider ready to be loaded.

 


Lets add some working code 

To a boot() method, we can add some code that will call some methods on a User model.

note:
All these functions (methods) in code above, can be grouped in observer class.
More about it: here.

Methods: creatingUser, savingUser, updatingUser in User model are simple:

If we register user (save user), we will run events: creating and saving which log messages:

If we update user (e,g, user click of confirmation link in email), we will run events: updating and saving which log messages:

 


Service provider allows easily to let your app run different tasks, when some Eloquent powered events fire.

Neat.