|

8 Steps To Success With Laravel Events

laravel events and listeners

If there is one thing I love, it’s automatic code generation. There’s nothing quite like having helpful commands and tools to scaffold out boilerplate code you don’t feel like writing. In this tutorial, we’ll take a look at how Laravel, and Artisan in particular, make it easy to add event functionality to your application. Events are an implementation of the observer pattern, where an event takes place, and then one or more listeners respond to that event. It can be thought of like something making an announcement to your application, and then actions being taken due to that announcement. Let’s see how we can set this up.


8 Steps To Success With Laravel Events


EventServiceProvider

You can begin setting up your events and listeners by populating the $listen array in EventServiceProvider.php. As a quick example, let’s see if we can set up an event where when a User logs in, we write that event to a file. Let’s see how to do that.

In the snippet above, we populated a UserLoggedIn Event, and it’s associated WriteMessageToFile Listener. These classes do not actually exist yet, but we will create them now via artisan.


php artisan event:generate

vagrant@homestead:~/Code/lpg$ php artisan event:generate
Events and listeners generated successfully!

Excellent! We now have an Event and Listener class to work with. UserLoggedIn.php was automatically created in the Events directory, while WriteMessageToFile.php was automatically created in the Listeners directory for us. Let’s not add any functionality to these yet, let’s just think of what our goal is. We want to write a message to a file when a user logs in. In fact, we should log the actual username of the person who logged in. Now at the time of this writing, the built in Auth scaffolding has been removed from Laravel. We can easily generate this system for us however by running php artisan make:auth. Once you have run this command, you will have the auth system to work with.


Find The file where you want to trigger the event

In our case, we are using the user login system that is automatically generated via php artisan make:auth. Now, our goal is to write a message to a file when someone logs in, so we need to find the location in the code where this happens.

In the AuthenticatesUsers trait, we find the following method

Maybe we can trigger an event here.


Include your Event class file via use

Before we can actually trigger an event at the location we want, we need to include the Event class that was generated when we ran php artisan event:generate. In our case, we created a UserLoggedIn.php class as our event. To make use of this, we simply include the following line in the file where we want to trigger an event.


Trigger an event with event()

Now that we have included our Event class in the AuthenticatesUsers.php file, we can update the method where we want to trigger an event.

This snippet above is where the magic is starting to happen. Before the return statement is issued, we added in some code to trigger our new event. We want to be able to determine who it was that actually logged in. This is the reason for accepting the $request as a parameter to the UserLoggedIn() instantiation. We will be able to access information about the user via $request when we deal with it in our Listener class.


Update your Event class

As it stands now, we have the plumbing in place to support events, but triggering this event at the moment will do nothing. Let’s look at our generated event class.

UserLoggedIn.php

At the trigger event location, recall that we wanted to pass in the $request object. We need to update our UserLoggedIn event class to support this. Simply type hint it like so (and add use Illuminate\Http\Request;).

That’s about it for the Event class. Notice there really isn’t any logic in it. Mostly it is just a data transfer object, or container for our event.


Update your Listener Class

The final step of our tutorial is to add the logic to our Listener so that triggering our event actually makes something happen. Recall, our goal is to write a message to a file that indicates who just logged into the application. Here is the boilerplate that got generated, before we add our logic. Recall we named our listener WriteMessageToFile, so that is the class name. In addition, our Event class is already type hinted for us on the handle() method. It is in the handle() method that we can add our logic.

Here is our updated file, with logic now in place.

Hopefully you can see how we are accessing the $request object we had passed in. In our Listener class, we simply access it as part of the type hinted Event class. So as we are used to using something like $request->user() to access user information, in this case we use something like $event->request->user(). In this file, we add use Storage at the top, because we are going to write something to a file. We prepare the $message to be written by accessing the user’s name, and concatenating a simple message to it. Once we have our message, we use the Storage class to simply write it to a file.


Test It Out!

Ok, once we create a user, let’s try logging in.
log in to test

Notice we are now logged in with the user name of “Leonardo”
logged in as leonardo

If all went according to plan, we should now have a text file in our storage/app directory with a message in it that indicates a user just logged in.
event success

Pretty Sweet! If you need more events and listeners, simply wash, rinse, repeat!


8 Steps To Success With Laravel Events Summary

In this tutorial we took a stab at creating our own events and listeners in Laravel. This approach works well when you have something occur in the application, and then you want one or more things to happen as a result of this. By leveraging Artisan, we were able to create boilerplate code with ease, and then simply wire things together to make it work.