Laravel 5.4 #15 : Events

Laravel has a feature called Events that allows us to fire an event and listen to it through the Listeners. To implement this feature, we will listen to the login event and save the login date to know how much of the last time a user has been logged in.

I have based on this article.

First of all, we have to add the field to the database. So, we have to create a migration:

Add this code:

Execute the migrations:


Now, we have to register the event and its listener. Open  EventServiceProvider.php and add this code to the $listen array:

Once this is done, execute the following command, which will create both the events and listeners in the array.

The event won’t be created because is native to Laravel, but the listener yes, it will be created. We can find it in  app/Listeners :

The handle function accesses the user sent from the event (Login), adds the last login date (which will be now) to the object and saves it to the database.

To display the value in the view, just put this:

If you want to format it, we can do it like this:

And will have to add to the model User.php this:


In this post we have only created a listener (LastLogin) since the event we use (Login) is native to Laravel, if you want to see how a custom event is created you can do it in the Laravel documentation, it is very simple