Get started with Laravel events and listeners

Video Statistics and Information

Video
Captions Word Cloud
Reddit Comments
Captions
hey everyone andrew here in this video i'm going to show you what exactly events and listeners are in laravel and how you can use them in your own applications let's start off with events an event is a class in laravel that lets us send out a kind of notification whenever an important change happens in our application so let's say we have an e-commerce store we would use an event whenever a user made a successful purchase we then use a listener class to hook onto that event and perform some action whenever it's triggered in the case of our e-commerce store and the purchase event we'd want to do something like send out an order confirmation email update the stock in our database or send an alert to the warehouse to start packing up the order and shipping it out so we have three separate listener classes for this one event class and that forms this kind of hierarchy where events have many listeners this is called an observer pattern and it is a common design pattern where we end up with this publish and subscribe flow okay so what does this look like in a practical application well i have this laravel app here and going off of our example earlier i have this dummy ecommerce checkout page set up the functionality for this form though is blank right now but let's go ahead and scaffold it out okay so whenever a purchase is made we should create a new purchase model in the database but we should also send out a confirmation email to the user and update the inventory which resides in another database table so first things first let's go ahead and create that purchase model so we can just say purchase is equal to purchase create and we'll use request only and pass in the parameters that make up a purchase okay so in order to test this let's just return back our purchase model and see if this works all right let me just fill out my details here and if we hit checkout we get back a successful purchase as json with the details that we added in now looking back on the functionality for this form submission which is just in the main routes web file we also need to send out a confirmation email and update the inventory now typically this functionality would reside in a controller method and as such you usually want to keep those fairly lean i like subscribing to the belief that separating out as much business logic as possible from the controller is usually a good thing i mainly want to focus on the data that's coming in and the data that is being returned which means that items like these two here i would want to refactor out somewhere else in our application that makes more sense and this makes a perfect use case for events let's open up our terminal here and we can use php artisan to make an event and we'll call it something like purchase successful so our event was created and let's go ahead and open that up so all generated events will reside underneath the app events directory and the same namespace and if we scroll down we see there's really not a whole lot to this class we have a constructor method here and a broadcast on method down here for the purposes of this video i'm not going to be dealing with anything like websockets so i'm not going to be broadcasting out the events that i'm creating so this whole chunk down here can just be removed if you would like i can talk about broadcasting events and using websockets in a future video just let me know in the comments below that also means that we can remove some of these unused use classes up here okay that's better so what do we do with this constructor method here well basically all an event class is doing is act as a wrapper or some kind of state object that we pass into it okay so what do i mean by that so in this constructor it's expecting either a model an object or a simple variable that we pass through to it so in this constructor it's going to be expecting something related to this event that we're going to be passing through to it usually in laravel those are model objects but they could also just be standard objects arrays or simple strings and integers in our case though our event is called purchase successful so we're going to be expecting that purchase model object that we had created earlier so in the constructor we are expecting a purchase called purchase and then we'll initialize that class property here as a public property called purchase and instantiate it in the constructor so we now set the class property purchase as the purchase that is passed in through the event and that's all we have to do here to set up an event now we have to deal with the other side of that which is a listener and like i said earlier listeners are where the action takes place after an event has been fired off so in our example we should be using two listeners one for sending out the confirmation email and another for updating the inventory now we could just have one listener that both sends out the confirmation email and updates the inventory but it's best to keep your actions separate as it will keep your classes short and easy to understand plus it'll be easier to identify potential errors that might crop up okay so let's start out with our first listener and just like the event we can use php artisan make listener and again the name should be relevant to what we are doing so in our case that is sending out a confirmation email so we can call this send purchase confirmation email and we have our listener created while we have the terminal open let's also create our listener for the inventory and let's call that update inventory after purchase okay now let's open up our first listener the confirmation email one and if we scroll up we can see that these are also underneath a new directory in app listeners so we'll open up our send purchase confirmation email class and if we scroll down we only have two methods that are present in this generated file we have a constructor like we did with the event and we have a handle method where the actual action is performed and you can see that the handle method has the event that's passed through it that we had created earlier this purchase successful event which means that we can access properties on that event as well which includes the purchase that we made and we're going to pass through to the event so we can reference that purchase by calling event purchase and any other properties that we set in our purchase successful class as public properties under here we can access with this event object that's passed through to our listener handle and we're actually not going to be doing anything with the constructor of this class so we can remove it and free up some room okay well what do we need to do in this listener well as we talked about in the main method for our form submission we're going to be sending out a confirmation email that details out the purchase information and the items that were purchased so our goal is to send out a confirmation email with the details of the purchase now i went ahead and already set up a mailable class here called purchase confirmation which sends out a markdown view file called purchase confirmation as well if we open up that you can see right now i just have a title and these are the fields where we'd add in the purchase details we'll have direct access to that purchase object so we can just say purchase name well actually it was first name and then last name and the rest of the attributes as well okay so now if we go back to our send purchase confirmation email listener we can finish building this action in which case that's just sending out the email so we use the mail facade and two it's going to the purchase email address that's added in the form and then we use send new purchase confirmation and we pass in that purchase object okay and this marks the end of this listener so now we can open up our second one and create the handle for this as well like with our purchase confirmation we don't need the constructor so we can get rid of that and remember this one we are going to be updating the inventory for each item purchased and the purchase which we get from event purchase will have an items column that's a json string containing both the id and the quantity of each product purchased so we can run a for each loop on json the code purchase items as item and that's it for this listener as well so reiterating this we have an event this purchase successful event that when dispatch will have two listeners send purchase confirmation to send a confirmation email and update inventory after purchase to update the inventory of the product table now how do we go about actually firing this off so in the method that handles the form submission all we have to do now is call that event class so purchase successful and dispatch and then we need to pass in that purchase object because remember back in the purchase successful class we are expecting that in the constructor which then gets funneled into our listeners and that's it so now this one line will handle sending out the confirmation email as well as updating the inventory in our application and let's just comment out this early return here as well now there is one more vital piece that we're missing though and that when this event is dispatched right now laravel doesn't know what listeners are associated with it so it will fire off the event but the actual actions of the listeners aren't going to happen just yet in order to make that connection we have to open up the event service provider class under the app provider's namespace under the app provider's namespace and in this you'll see we have this associative array called protectedlisten what this acts as is a connection between events and their listeners so out of the box right now laravel contains this connection right here which is whenever we have a auth registered event happening so whenever a new user is registered it fires off this send email verification notification class which is a listener that fires off some kind of notification for verifying your email and we can add our class and listeners to this just as easy so under the one that's already here we can call our class that we created purchase successful and then it is the key of an array of listeners that get fired off whenever this particular event is triggered and we can just add in the two that we had created earlier so we have send purchase confirmation email and update inventory after purchase and that's it and you can have the same listener under multiple events all you have to do is just add them to each key of the event that you want to be associated with them so for instance under this registered event here we could also send a purchase confirmation email it wouldn't make sense though because what's coming through this event is not a purchase object so this listener would fail but i just wanted to show that you could add as many listeners to as many events as you would like and they can be shared between them okay so now it's time to test this out we have everything set up so now when we go to submit this form it should create a new purchase and then fire off the event passing in that purchase which will send out an email and update the inventory so back in our browser let's fill this form in one more time and we'll hit checkout and we landed on a blank screen but that's kind of expected because we don't have any return after this line which is kind of my bad but anyway we can test out and see if our event actually worked so i have mail hogs set up so we can trap the emails coming through locally if i just go to localhost 8025 we can see that i have my purchase confirmation email and opening it up we can see i have all the details of my purchase object as well as the items that were included so we know at least one listener fired off successfully now how about the other well opening up table plus let's go to our products table here and if we go over to the quantity column we have one missing from the first and two missing from the second which exactly matches the quantity of items that were purchased so both of the listeners for our event fired off successfully and made changes to our application while allowing us to have a much more streamlined code for handling that form request now what we accomplish here is creating our own event that we fired off in line in our code base but like we saw in the event service provider class laravel does come with some events already included that you can hook into and just create your own listeners for them some of these are under the illuminate auth events namespace which if we go here we can see attempting authenticated failed which is what happens when someone logs in with the wrong credentials or attempts to log in with the wrong credentials a login they log out password reset and etc and these are just ones for authentication there's plenty of other events that you can hook into you can find them by looking through the layer of all code base under any events namespace and all you have to do is then add them into this listen array here and create your own listener classes that fire off whenever they're triggered let's say that we want to log every failed login attempt using that illuminate auth events failed event then you might create a listener called log failed login attempts which would gather all the data from that login attempt like the user's email address they tried or the ip address and store that somewhere in your database or your logging record of choice anyway i think that's it for this video hopefully you now have a more solid understanding of how events and listeners work in laravel and how you can use them to streamline your application's code thanks for watching
Info
Channel: Andrew Schmelyun
Views: 9,787
Rating: undefined out of 5
Keywords: laravel, php, laravel tutorial, php tutorial, laravel events, laravel events and listeners, laravel beginner tutorial, laravel beginner, web dev, web development
Id: vewcmfCnYLY
Channel Id: undefined
Length: 15min 37sec (937 seconds)
Published: Thu Apr 28 2022
Related Videos
Note
Please note that this website is currently a work in progress! Lots of interesting data and statistics to come.