|

Laravel Event Listeners

Laravel Event Listeners

When using Laravel, there is a great way to listen for events and then take actions based on those events by using the Event Facade. This is also known as an Observable Implementation. By using the Event Facade, we can listen for or subscribe to events that may occur, and then immediately take action. It’s a great way to keep your code clean, as well as having a dedicated class to handle events.

Why Use Event Listeners?

In your application, there may be many things that you will need to respond to. Maybe you want to respond to a user logging in, or logging out. Perhaps you would like to send a welcome email to a new user that just signed up, or send a goodbye email to a user that just deleted their account. There are all kinds of things you can use these event listeners for. Yes these things can all be done in the controller, but maybe it would be better to just set up some event listeners so we can just fire an event to take care of things like this.

Using Events in Your routes.php file

Putting events in your routes.php file is good for testing or for small apps. We’ll take a look at a better way to store your Laravel Events later on, but for now, let’s just whip up a few easy ones in our routes.php file for fun. We can start with Event::listen() and Event::fire(). This one example deals with a user logging in, and then taking an action based on the login event.

routes.php

When we visit the homepage, we’ll see the event fired successfully string 'a user just logged in' (length=21).

Passing Data to an Event Listener

We can also pass data to the listener. In this example we’ll grab a user from the database, then fire an event. When we fire the event, we can pass the $user as the second parameter. In our listener, we can then accept that argument to the closure and get access to it’s contents:

You can use the Event::fire() and Event::listen() methods anywhere you like. Often times, you can use them right in your controllers.

Dedicated Event Class

A different way to use event listeners is by way of the Event::subscribe() method. With this approach, you can instantiate a class directly, or pass a string to the method and Laravel will try to instantiate that class from the IoC Container. Let’s look at an example of how to do this.

The above code places our event handling in a dedicated class. In this case we name it UserEventHandler. Then, we can use Event::subscribe(‘UserEventHandler’) to listen for events to get fired. In our home route, we then fire the user.logout event, and its associated listener triggers it’s logic which in this case is to simply echo out to the screen that the user has logged out.

Add More Events to the Class

Now that you have a dedicated class to handle events for your users, you can track what they do like the dickens! Set up a listener for whatever you like. You could have a login, logout, newsletter signup, and more. The order of operation to add more listeners is to add the additional listeners to your subscribe() method with in your new class, define those additional methods to take action, then fire those events where ever you like. Let’s see what it looks like:

Where to put Event Listeners

So this has been very helpful so far. We are setting up event listeners and taking action on those events both with and without a dedicated class. We have been able to get this to work in the routes file but that is not going to be a good place to put these listeners. Following the Laravel File Structure examples, we’re going to create a dedicated Handlers folder to hold all this stuff. The steps to set this up are as follows:

  • 1: Create The Namespace

    In this example we have a laratut namespace within our app folder. So within laratut, we can now create a Handlers folder to hold our new class. Just remember to have the psr-4 autoload registered in your composer.json so that Laravel knows where these files live. For this example our snippet might look like this "psr-4": { "laratut\": "app/laratut" } although yours might be different depending on your namespace. If you’re not sure about your psr-4, check out the Composer Autoloading Tutorial.

  • 2: Create Event Handling Class

    Within your new namespace, create the new class file. We name ours UserEventHandler.php In this file, we just remove the class we had previously defined on the routes file, and place it in this file. Do note however that you now need to make a few namespace updates in this file, since it now lives in a different namespace! Basically, you need to add your particular namespace at the top of the file, as well as prepend the hardcoded controller methods with the namespace. In this example the namespace is laratutHandlers so at the top of the file, we just add namespace laratutHandlers; and prepend the namespace to the controllers like you see here. Our updated file now looks like this:

    UserEventHandler.php

  • 3: Register Subscription

    We still need to have a way to register the subscription so that we can listen for when events get fired. Before we simply had our event subscription in our routes file and all was good. Now that we have moved everything to a namespace, we’ll need to include the namespace when passing the string to the subscribe method and if you don’t want that cluttering up your routes file, you can simply move it to app/start/global.php after the App::down() method like so:

  • 4: Enjoy Cleaner Code

    Look at how clean and classy your routes file is now!

Awesome! When you visit the homepage now, everything still works, and you now have a dedicated class where you can add as many listeners as you like to take action on fired events. Lots of fun indeed!