Ep48 - Broadcasting Events and Websocket Channels | Laravel API Server

Video Statistics and Information

Video
Captions Word Cloud
Reddit Comments
Captions
[Music] hey there sam in the previous lesson i mentioned that every app event is broadcastable to the websocket clients let's discuss further on this topic in short when we want to broadcast our app event laravel requires us to broadcast these events through something called channels there are three types of channels in laravel the public channel presence channel and private channels when websocket clients want to connect to our server they'll need to subscribe through one of these channels provided by the websocket server here's how they work a public channel does not need authentication and anyone in the world can connect to this channel presence channel and private channel requires authorization and the difference between presence and private is that the presence channel is aware of all the users that are currently connected to the channel in other words all the users in the presence channel can see the information of each other this is perfect for chatroom application where the users know who is online who's offline who posted this message and that message so on and so forth a presence channel is useful when the identity of the user connected to this channel is important to the application private channel on the other hand is for situations where we don't want users to know each other and we simply only want authorized user to connect to this channel we can use private channel for general purposes for example getting all the login user to connect to the same private channel in our app so that we can easily broadcast notification to all of our users we don't need each user to know each other so in this case a private channel will be perfect alright now let's look at how we can broadcast laravel app events and define broadcast channels the first thing that we need to do is to go to our appconfig file and uncomment the broadcast service provider under the application service provider section the broadcast service provider here is different to the one provided by the core framework listed up here the purpose of the core broadcast service provider is to set up the necessary code for broadcasting to work in laravel while the one down here is for us to set up our app broadcast service logic like defining the channel authentication routes setting up the middlewares and so on and now if we look inside the service provider we can see that it is a very simple service provider class containing only two lines of code the routes function from the broadcast facade will register the authentication routes for presence and private channels to work and line 19 here will register the authentication routes for private and presence channels that we define inside the channels.php file leaving inside the routes folder let's take a look inside it and as you can see here this file is pretty similar to the other routes file that we have in our app but instead of using the route facade we're using the broadcast facade here and we're defining a channel this time not a route endpoint the syntax is pretty similar to its route counterpart so the first argument is the channel name and the second argument is a callback function that will determine whether the current authenticated user can subscribe to a given channel or not the first argument in the callback function is the instance of the current login user and any subsequent argument represents the value of the placeholders in a channel name so in a sample snippet here it is representing the id placeholder in the channel name for a private channel we'll need to return a condition and if the condition is true that means the current authenticator user will be able to subscribe to this channel in a presence channel however in order for us to authenticate a user we need to return the user information in the callback function rather than just returning a boolean we will discuss more about this in the next video where we'll look at how to connect our front end to the back end but here is a simplified overview on how websocket authentication work in laravel so here's the client and here's a server when a client wants to subscribe to a private or presence channel the client will first send a http request to the server that is directed to the off endpoint in laravel which is by default slash broadcasting slash off upon receiving the http request laravel will then trigger the callback function as we define in a channel.php file if the callback function returns a truthy result then the server will return a success response back to the client with the appropriate metadata for the client to establish a successful websocket connection with the server in a subsequent request the data in the http response is mandatory to make this websocket connection now if the callback function that we define in the channel.php file is returning a full series out then the server will return a unsuccessful response and therefore the client cannot establish a websocket connection with the server this initial http request and response is what we call as handshake okay now let's look at how we can set up our event classes to get laravel to broadcast them to the websocket clients and just for demonstration i'll be creating a dummy event class let's go to our terminal and type in php edition make event and our code playground event and now let's go to our newly created event class and the first thing that we need to do in order to make this class broadcastable is to make it implement the should broadcast interface laravel will automatically broadcast any event classes that implements the should broadcast interface and now if we scroll down a little bit more we can see that as a function called broadcast on this is a function where we define which websocket channel that we want to broadcast this event on and by default laravel has made this event to broadcast on a private channel and now just for demonstration i'll change it to a public channel instead which will just be the channel class instead of the private channel class now the first argument in a channel constructor is the name of the channel now our app could have multiple websocket channels so it's a good idea to have some sort of naming conventions otherwise our channel names could go our hand very very quickly personally i like to name my channel in this way first i'll start with the channel type in our case here we are broadcasting on a public channel so it'll be public followed by a dot the second part will be the resource name and most of the time it'll be a model name in our case here since we're creating a dummy class so i'll call it playground you can put as many parts as you want but for the final part i always like to use it as the channel number or the channel id i'll hardcoded as one for now channel numbers or channel id is great to manage websocket events for example if someone is working on post number one you wouldn't want events from post number two to affect post number one do you that's gonna cause chaos and never gonna lead to a happy ending all right let's test if our event is working we first need a way to send out this event so i'll go to the web php file and in a playground dummy endpoint i'll fire an instance of the playground event and now we'll go to our terminal and start our websocket server by typing in php addison websockets serve once we're done let's go to our browser and visit the debugging dashboard provided by laravel websockets let's click on the connect button and you should see some events pops up in the event list and if we go back to our terminal you should also see some debugging messages inside the terminal okay now we'll attempt to call the playground endpoint to fire an instance of the playground event let's click on the send button oh no we see an error it says pusher error off key should be a valid app key now in the last lesson i mentioned that laravel websocket is a pusher drop-in replacement we will need to configure laravel to use larvae websocket as the websocket server rather than using pusher to do that we need to go to the broadcasting config and in a pusher driver we'll add in a few more options by putting in the host and port we can define our own custom websocket server address and since we're not using any ssl certificate we should set use tls and encrypt it to false okay now let's go back to postman and try again and we see a 200 response fantastic let's go back to the browser and look at the debugging dashboard and we see a new event popped up in an event list which is our playground event and if we go to our terminal we can see that our event is logged in a console with the event name and the channel name and as you can see here the default event name is the fully qualified php class name of our playground event and here's a question what if i want to use my own custom event name the answer is super simple we just need to define another function in our event class and the function name is called broadcast s and we should return the custom function name that we want i'll call it playground for now let's test our code we'll go back to postman and set another request and back in our browser we can see there's a new event popping up and now with a custom event name called playground great we can also attach information inside the broadcasted event where the data attached in the event can be used by the front end to do that we need to go back to the event class and define a new method called broadcast with and whatever we return in this function will be attached as part of the event payload so here i'm just gonna return a simple dummy array and we'll go back to postman and try to send another request and now if we go to our terminal we can see that the latest event contains a payload in the data field and it is exactly the same as what we put in inside the broadcast wave function isn't that neat so that's a basic intro on broadcasting in laravel and how to broadcast an event we'll discuss further in the next lesson about the front end private channel and presence channel i'll see you there key takeaways for this lesson if a websocket client wants to subscribe to a websocket channel in laravel the client will first need to perform a http handshake in other words to authenticate the user before establishing a persistent websocket connection event classes will need to implement the should broadcast interface before laravel can broadcast them to the websocket we'll need to configure the host and port of the pusher driver in broadcasting.php config file to get laravel to use our self-hosted laravel websocket server otherwise laravel will attempt to use pusher out of the box by default laravel will use the event fully qualified class name as the event name if we want to use our own custom event name we need to define the broadcast as function inside the class we can attach data inside the event payload by defining a broadcast with functions inside the event class that's it for now and i'll see you again in the next video if you enjoy the content of this video don't forget to hit the like subscribe and the bell icon for more content to come it will really help me out thanks for support [Music] you
Info
Channel: Acadea.io
Views: 9,085
Rating: undefined out of 5
Keywords: websockets, config, broadcasting, broadcast, real-time, real time, pusher, events, laravel
Id: NMstI0hghnE
Channel Id: undefined
Length: 11min 25sec (685 seconds)
Published: Tue Apr 12 2022
Related Videos
Note
Please note that this website is currently a work in progress! Lots of interesting data and statistics to come.