Laravel WebSockets Course | Chat App Example

Video Statistics and Information

Video
Captions Word Cloud
Reddit Comments
Captions
hello and welcome back to another aht cloud training series in this course we will cover custom websocket implementation using the laravel framework we will not be using any third-party vendors we will use our own server to handle all the websocket communications before we get started don't forget to subscribe to my channel to stay up to date with my latest training videos the first part of the course i will explain what websockets are and how they work then we will build a sample chat application this is not a front-end course so i will not be focused on aesthetics but rather on how to establish a two-way communication system between your server and your user devices here's a quick demo of what we're going to be building so i have my my application open on two browsers for the first one i'm gonna connect using my name and here i'm just going to connect without anything i can send a message so let's send an example message and you can see on both browsers we see the message without refreshing our page and let's try here and you can see here i did not enter my name so it shows as anonymous websockets is basically an api that lets you establish a two-way communication system in real time between a user device and your server a user device can be for example the user browser or their mobile phone or anything that can connect to your server a great example is a chat application let's say one of your users has his mailbox open on his browser and someone sent him a message then we don't really want that user to keep refreshing their browser to get those updates rather we want to do it without having them to refresh their browser connecting to sockets is very similar to how you would connect with http requests to make an http request on a server it's usually done through ports 80 for http and ports 443 for https websockets use a very similar but different protocol to make a websocket request instead of using http you would use ws usually on port 6001 the https equivalent is wss and you can do that on port 443 pusher channels is a popular hosted websocket solution instead of building your own websocket server you can use theirs for a certain price in this course we will learn how to implement our own websocket server instead it's free very easy to do and gives you full control of your system beyond code laravel websockets is a package designed for laravel 5.7 and up it can be used as a pusher replacement this means you can still take advantage of using laravel's pusher configuration and push your sdk files without using their servers this can get you up and running with websockets real quick i have already prepared my project on vagrant homestead if you don't know how to set up your local environment i suggest you watch my previous tutorial on how to set up your local environment i am using homestead so i'll show you my homestead configuration file so you can see here i configured this domain to be our local host i am using php 8.1 to create a laravel project i am going to be using composer so what you have to do is run composer create project and this is for laravel slash laravel and i want to create it in my current directory here once that's done it should look something like this now let's go ahead and create ourselves a new database i am using heidi sql as my database client so in here i'm going to create a new database and let's call it chat app and i'm going to be adding this to my emv file let's go ahead and open the code on visual code or whatever editor you're using and in here we're going to go to our emv file and we're going to be configuring our database connection so i'm connected using my homestead my database name was chat app my username is homestead and my password is secret we will be using a queue to process our events i recommend you use something like redis for your q driver if you don't have redis setup you can just use your database instead inside your emv file you should have a variable called q connection i'm going to change this to database if you're using your database as a queue driver then you will need to create a new database table to hold all your jobs let's go back to our terminal to create our new table we can just use the level uh built in command which is php artisan q table and this will create a new jobs table for us so let's go back to our code and if you go to database migrations then you should be able to see that you have create jobs migration here and you can see it creates you a jobs table let's go back to our terminal and let's go ahead and run our migrations before we install laravel websocket package let's go ahead and find the documentation for it i want you to search for beyond code websockets and in here you should see the first result beyond code dot or beyond code dot d e and in here you should have the installation instructions to install laravel websockets there is four things we need to do we're gonna install it through composer then we're gonna publish the migration files then we're gonna run our new migration files then we will need to publish also the websocket configuration file let's go ahead and install the laravel websocket package and to do that with composer you run composer require beyond code slash laravel dash websockets once that's done let's go ahead and publish our migration we're gonna copy this chunk of code and let's paste it in our terminal and we're gonna run php artisan migrate and the last step is we're gonna publish our configuration file once that's done then you should be able to see here that you have a new configuration file it's copied from this location to your config folder it's called websockets.php don't worry about it yet we will cover it in a bit to install pusher's php sdk we will need to use composer so we have to run composer require pusher slash pusher dash php dash server now we're going to run our queue and our websocket server to run the queue on one terminal you want to run php artisan q work to run the websocket server you will need to open another terminal and you'll need to run php artisan websockets serve so far we have installed uh pusher php server to run locally on our server and we also installed the laravel websockets package now let's go ahead and configure our application to work with our websocket server let's go to our emv file and let's scroll all the way down here you should see your pusher app id pusher app key secret and cluster so for all these values instead of using the actual pusher server we're just going to use ours so here you can write staging and this can be any valid string all right now we need to make sure that our broadcast driver right here is set to pusher and to be consistent let me just copy this and paste it here alongside the other pusher variables let's go ahead and add two more variables laravel websockets host and laravel websockets port and this port is going to be 6001 for the websocket host it's going to be your ip address so your local host if you're running it on localhost i am using vagrant homestead so i'm running my my project on a virtual machine so i'm gonna have to use my ip address if you're using the same setup as me then you should be able to find your ip address inside your homestead.yaml file and now we're going to configure our broadcast file so this is where we're going to configure our laravel application to run with our websocket server so you want to go to config and you should be able to find a file called broadcasting.php and here we have a pusher option this is what we want to be modifying so the driver should be pusher and the key secret in app id is all coming from our environment variables that we set which was staging for the options let's go ahead and set the use tls to false so we want to set scheme to http and we want to add the curl options so for the curl options we're going to add the curl option so opt underscore ssl verify host and we want to set this to zero this is just so we can run this locally we want to also do the same thing but for the verify peer so in the last year we're going to change the host to peer now let's go ahead and add our websocket host and port variables so i'm just gonna copy cluster copy it two times and for the first one we're gonna need our host variable which is your laravel websockets host and we're gonna also need to do the same thing but for the port so let's add it here this should be pretty much it for our broadcasting.php file the beyond code level websockets package that we installed comes with a dashboard that you can use to monitor your websocket connections to access your dashboard we're gonna go to config and inside here we're gonna scroll down and you're gonna find the file called websockets.php and here you can set your custom configuration for your dashboard we will cover this in a bit but for now let's just uh scroll to path so you need to find this variable path and here you can see the path is level websockets so you want to open your browser and let's go ahead and open our project and you want to go to this path that we copied and you should be able to see your websockets dashboard here as of now we have not configured our dashboard so connecting to our websockets is not gonna work but i wanna show you how to uh handle or debug errors uh when it comes to connecting with websockets on this page i'm going to open developer tools if you're using windows you can just use ctrl shift i and i'm gonna go to network and let's try to connect so it's saying that channel current state is disconnected and it did not work so here you see we have a status 101. let's go back to our websockets configuration file we want to set the dashboard configuration here so we want to set the port and the host if you remember inside our emv file we made the two variables level websockets port and host let's go ahead and copy this and we want to set that inside our websockets file so here under port let's add our host now let's scroll down and let's configure our app so in here our id is set to the pusher app id which is correct the app name is also coming these are all coming from our emv file is the app name here the key is also set inside our emv file which is staging secret path we have also uh capacity so let's copy uh the port in the host from here and let's also add it to our apps variable so i'm going to add it on top of everything now let's go ahead and add a new variable and this is just for our development purposes you should not enable this in production but let's say encrypted is set to false now remember any change you make inside your websockets file or any change you make for your websockets it's not going to reflect until you restart your websocket server so let's go back to our terminal where we had the websockets running so here we need to exit this so ctrl c and let's go ahead and run it again so php artisan websockets serve now let's go back to our dashboard and let's refresh our page and let's try to connect now let's go back to our dashboard and let's refresh our page and let's try to connect now let's close the developer tools and you can see here we're connected so these are some events that happened so every time you connect to your websockets or you do anything relating to your websockets let's go back to our terminal you should be able to see to see it here so there's a log for it here now let's go back to our website and so far we can connect to our websocket server but let's test out if we can send to our server so in here event creator go ahead and add any name for the channel add anything for the event and for the data make sure to add two curly brackets so it must be like this now i'm going to send this and actually go ahead and open as well your developer tools and send a few requests now you can see here this is pending and it's taking a very long time eventually it will time out and give us an error and eventually you should be seeing this alert that's saying error sending event let's go ahead and click ok on this and you want to take a look here so you see we have a status 500 internal server error so whenever this happens you should be able to see this inside your log file as well judging from this error here it's saying pusher error failed to connect to this url api mt1 pusher.com now i can say here that the problem is for some reason our configuration file is not being read correctly for pusher so let's go back to our code and we want to go to broadcasting.php and here i have a mistake so for the layer of websocket host it should be here host i forgot to change that and i left it as cluster so that was not working let's go ahead and try again connect and you can see it worked now let's send a few more and you can see our messages here so far we have set up our websocket server and we made sure it works using our own dashboard now we will create a new api so that we can connect to our websocket server let's go ahead and create a new controller file so inside apps you want to go to http to controllers and in here let's create a new file and let's call it sockets controller now let's go ahead and create an empty class here so we're going to use declare strict types we're gonna set that to one we're gonna also add our namespace and that was under app http and controllers and let's go ahead and let me just add the end of the line terminator there and let's add our new class here so let's call it uh sockets controller and let's go ahead and create an empty method just to handle our connection so we're going to call it connect and we're going to need to use the request object from http so you need to make sure it's not the support one the support facade it's coming from the illuminate http and let's go ahead and add our request and just for now let's just uh dd a message just for now now let's go ahead and create our api endpoints and point it to this controller to create an api endpoint we will need to add an entry inside our router file so let's go to uh routes and in here let's go to api now for to make this uh course a little bit more simple we will not add any authorization or middleware but you can always add your route inside middleware and require authentication i'm going to create a new post api and let's say sockets slash connect that's gonna be our api endpoint and we're gonna point that to our sockets controller and the method was connect now let's go ahead and just test this route out make sure it works i'm gonna use postman to send a request if you don't have postman installed which i really recommend you install if you're getting into developments you can just switch your route to a get instead of a post and you can just use your browser just for now so our endpoint was socket slash connect and then there's the api let's add that here so api slash socket slash connect and this would be the full url let's go ahead and send this and let's preview so i can see that our controller is handling the request now let's go back to our controller file now let's go ahead and erase this line and we're gonna have to create a new broadcaster so to do that we're going to use we're going to basically declare a new instance of pusher broadcaster and let's uh go ahead and add a parameter is going to be a new pusher instance as well so that's going to be new pusher and if you don't see these in your autocomplete you want to make sure that your ide is actually showing you uh what you have inside your vendor so it should be under vendor if you scroll all the way down you should have a pusher right here and you should have another folder called pusher server sdk source and you should see your pressure file this one the constructor we expect three four parameters actually so we have the f authentication key which is our let's go back to our emv file which is going to be our pusher app c uh app key and we have our secret app id and our options so let's go ahead and add all those here and since these are coming from our emv file we can just use the emv helper method so let's just copy the app id and we need another one for so the first one is going to be app key the second one is app secret the third one is app id and then for the last parameter the options we're just passing in an empty array so now that we have our broadcaster instance created let's go ahead and return a valid authentication response so we're going to use our broadcaster and let's return a valid authentication response now we're going to be creating our front end so far we have not modified our front end at all so let's uh go ahead and do that so we want to go to resources and in here you want to go to views and this is the default laravel page which is this one here let's go ahead and delete this and create a new file so we're going to create a new view and let's call it chat app example dot blade dot php and let's go ahead and modify our api route for that so we're gonna go to routes web and it should be this one here so we want to return our chat app example row and let's see if that worked so let's refresh our page here so now we're getting a blank page let's go ahead and create an empty html page so we need an html tag we're gonna also need a head tag and we're gonna also need a body tag all right so inside the head the first thing i'm gonna do is add a title and let's just say laravel websockets chat example now i'm going to be adding the jquery cdn so let's go to uh google and let's search for jquery cdn and let's go to the first result and here let's select the latest version and we're gonna get the minified version let's copy this and let's paste it in our head tag now let's go ahead and grab pusher cdn so we're gonna search for pusher cdn and here let's go to js.pusher.com and in here you want to click on the last link here the stable release in the docs and go ahead and copy this script tag now we're gonna also need to add vu so let's go and search for vo2 cdn and you should have a cdn js.com the result here let's go ahead and copy version let's grab version two point uh the latest two version that's going to be 2.6 and let's copy and in here make sure you copy the women js all right now let's go ahead and grab bootstrap 5cdn and it should be inside the first result let's copy the css and let's copy the yes so it should be this one here now let's go ahead and grab pusher cdn so we're gonna search for pusher cdn and here let's go to js.pusher.com and in here you wanna click on the last link here the stable release in the docs and go ahead and copy this script tag now we're gonna also need to add the vu so let's go and search for vo2 cdn and you should have a cdn js.com the result here let's go ahead and copy version let's grab version two point uh the latest two version that's going to be 2.6 and in here make sure you copy the woomen js all right now let's go ahead and grab bootstrap 5cdn and it should be inside the first result let's copy the css and let's copy the yes so it should be this one here now let's go ahead and create our body so the first thing i want to do is create a new tag let's give it class container and the id app this is for vu you don't have to use vu i'm just going to make a life a little bit easier all right now before we do anything else let's go ahead and create our view application so we're going to add the script tag right on right on top of the ending tag for body and i'm going to create a new application so we do that by writing new view and we want to pass this an object here so we will need to specify the element for the app and the tag is id app here so let's grab that and let's say we want to declare our data object and for now we don't have anything in there and we have two methods that we want to work with mounted and this will run once the app is mounted and the methods so this is where we can declare our functions all right now let's go ahead and create a new card so we're gonna use a bootstrap cards so we're gonna create a new div card margin top four let's add our card header this is where we're gonna have the disconnect and connect buttons and let's give it padding of tool this is just for design and let's add a new form here now inside the form let's go ahead and add two more columns so the first one is going to be uh so let's say a column for the large screens we want to have size 2 for the medium screens is going to be 3 for the small screens is going to be 12. let's also add margin on the top and set the padding to 0. now let's copy this and let's uh duplicate it and let's format our file so for the second one i'm going to use column for the large is going to be one and let's set the medium to uh two and let's leave the small to 12 and leave the rest here so for the first element i'm going to add here our label and let's say you want to write your name here then i'm going to be adding an input value so let's say input class form control this is bootstrap five form control small to make a small input button here and the placeholder let's say name and let's go ahead and just see how this looks in our browser all right so we have our name here let's add our connect and disconnect buttons so here i'm going to add a new button so for the class i'm going to add a margin on the right of two and i'm going to use a small button here i'm going to use the primary for the connect and let's give this with full width so let's say connect and let's copy this and add a new button under it and let's call it disconnect let's see how that looks in our browser all right let's just change the disconnect button to red so i'm going gonna here say danger instead of primary and let's see that worked all right let's go back to our code now let's go ahead and create some variables to capture our input so inside our vu app we have data in here let's add two variables connected and i'm going to set this to false and let's say name and i'm going to set this to null and let's go ahead and add these here so for the name here i'm going to add the v model which is going to be name and this will set our name variable to track the value inside this input now for the connect and disconnect i don't want to display them at the same time so inside the connected we're going to add the case so if vf we're going to set it equal to if the connected which is this variable here if this is equal to true then we actually if this is equal to false we want to display our connected button if it is equal to true we want to display our disconnect button and let's just test this out quickly and here let's refresh now let's go ahead and add our on click handlers for the connect and disconnect buttons so inside our vu app in methods actually this is a mistake we should remove these uh it's not a function it's a variable so let's go ahead and add a connect method and let's add a disconnect method just for now let's just set our connected variable so we want to say this dot connected we want to set it to true once we connect and to false once we disconnect now let's go ahead and call these methods once our buttons are clicked so for the connect method i'm going to say v on click and set this to our method connect and let's do the same thing for the disconnect let's copy this and paste it here and let's just change the method name to disconnect so let's go ahead and test this out let's refresh our page let's see so you can see now this is changing all right so now we're going to build out the card body this is where we're going to be placing all our message contents so in here under the card header let's create a new tag and the class is going to be card body and we will add the title here so let's add the h4 tag and let's uh give this a margin so margin thought is going to be four and let's let's say the title is message and let's go ahead and add a form under it before we build out the form let's go ahead and build the area where we would see all the incoming messages before we actually do that as well let's let's go ahead and create a new variable so under data we will create a new variable and let's call it message and message is going to be an array now let's go ahead and give our message some values so it's going to be an array of objects that will look like this we're going to have the message and the message is going to be let's say for example your message for some value and we're going to also have a name field and we're going to have a time field all right so message is an array of objects now let's go ahead and display these messages so on top of the title that we added for message in here we're going to add a new column and it's gonna be full width so column 12 we're gonna use the background light on this one and we're gonna set the padding top to two the padding on the bottom to two and the margin on the top three and inside this container we're going to add p tags so to write our message in here so the class is going to be we're gonna set the padding to zero the margin to zero and the padding for the start to two and the padding for the end to as well two so we want to use vu here and we're going to say v4 and let's uh add this in quotations so v4 message and index in incoming messages or in message what was the variable name that we declared here message let's actually change this to incoming messages so we want to loop through this variable this is the index so let's say here is one this is the first array value the second one would be two and the message is the actual value of each iteration so it would be for example this object and for each value in that array we're going to display a p tag and we're gonna give it uh we're gonna actually display the value here so let's say we're gonna first display the time so since we're using blade and view together we have to actually use this symbol to connect to our variables in here otherwise if you use something like this then it will be interpreted as blade rather than view so let's say message time so message.time we're indexing this variable here so we're gonna also display in bold the name so message.name then we're going to display also the actual message so let's say message.message and let's just quickly test this out on our browser let's refresh our screen and we can see here we have a message now we're going to build the part where we actually can enter our message and send it so under the card body here where we have our form let's go ahead and add a new row in here and we're going to give it margin two on the top all right so in here we're going to add a region to display any errors so we're gonna say a new uh we're gonna create a new div here and we're gonna give it column 12 we're gonna set the text color to white and inside this one we're gonna add another div here and we're gonna give the background to red so bg danger and we're gonna give the padding two and we're gonna set the margin on the bottom as well to two all right and let's go ahead and display here our errors just for now we're going to add the static error so let's say uh we're going to give it padding 0 margin 0 and the error let's just say in bold let me close this tag so in bold we're gonna say error invalid message and let's just go ahead and test this out and you can see our error messages here now there's just one more thing we need to do for this error tag we're going to only show this when there is an error so let's add a new variable under data and let's just call it form error and let's set it to false so this is going to be a boolean variable that will display the error once it's true so inside here under the row for the column 12 we're going to say v show if the form error is true now under the form error we are going to uh add the region where we can write our message so let's just close this and here let's start a new column so let's say column 12 and uh let's uh add this tag here and we're gonna create also another div and it's going to be for the form group and under here we're going to add a text area and the placeholder let's just say your message for the class let's give it form control and let's also give it three rows by default three and let's close this text area now let's just add a new variable to capture the value of this text area so in here under incoming messages i'm just going to add message and let's just set it to null so in here we're going to add the model which is going to be equal to the message actually let's just add this to the very beginning right before text holder all right let's just see how this looks now we just need to add the send button in here so that's pretty easy let's uh [Music] let's close this rows here and let's add a new one and we want to align the text here to the right and let's uh give this margin top 2. so we're going to add two columns so the first one is going to be on large screens is going to have a padding of 10 or it's going to have a width of 10 and our button is going to be on another column which is going to be smaller so it's going to have a size 2 so column large forgot the dash here and let's close this and add our button right here and let's just say send event all right so for the button we're gonna assign a type button and let's give it class btn btn small to make a small button and let's set it to success to have a blue color or actually let's keep it primary it's going to be blue success is green and let's give it full width let's see how that looks all right let's actually make it green let's say success all right let's see all right so now we're going to add the method where we can handle the on click for here so under methods let's add a new one and let's just say send event or send message and for now let's just set once this is clicked let's set the error to true all right and let's just try this out okay looks like it's not showing oh yeah we did not connect the method here so let's just say so now we're going to uh connect our method so v on click we're gonna set that to our send message function now let's just try this out all right i think i like the blue more so let's just go back and change this to blue so we're going to change the success to primary now there is just two more things that we need to do to fix our front end and we'll be done the first thing is we need to make this button smaller not sure why it's showing way too big and we also need to display this area only when we are connected so let's go back to our code and if you look here where we added our button this is supposed to be column 12 not co so i forgot to add an l so that should fix the long column and let's go ahead and comment out this message here because we're gonna set this out once we receive a websocket connection and let's uh go ahead and display this only when we're connected so we're gonna scroll up all the way to the card body and let's minimize everything and let's add a condition here so it's going to be vf when we are connected so when connected is equal to true let's try this out now let's go ahead and create our connect method here but before we do that we will need some variables so we can connect with our web sockets let's go back to our web.php file inside our routes and in here we want to change our return so we're going to add here beside the view we're going to add variables so we want to send all our pushing variables in here we're going to add our ports and this is coming from our emv file if you remember we created here our laravel websocket host import variables so let's add them here so we have our port we have our host i'll just change this name port and we also need our new authentication endpoint and if you remember we created the inside our api file it's this one socket slash connect and let's just add the api prefix here we also need to have our log channel this is for our this is coming from the beyond code level package and so you can just use a dashboard logger and it's inside the beyond code blurb of sockets and in here we wanna add our log channel prefix our last variable is we want to pass in our app so we can grab that from our app service provider so inside the function name here let's use dependency injection to grab the app provider and we want to use the beyond code app provider so it's this one right here let's make sure the name spaces are correct and here you can see they're both coming from the layer of websocket package and the name of this is called apps provider and inside our variable here let's pass in all our apps values and that was actually called app provider right that should be pretty much it let's go back to our chat application view and from here i'm going to actually open my web file on the right screen so what we want to do is we want to create variables inside our script tag for our vo application that will contain these values here so i'm going to do it under connected let's go ahead and add our new variable so we're going to have one for pusher let's set it to null we're gonna have one for app and let's set this to null we're gonna also have one for apps let's set this to null as well actually for this one apps is coming from our web.php file so we're going to use blade syntax to grab these variables and that's going to look like this and the variable name is apps let's actually copy this a few times and we're going to add one variable for our log so let's rename this to logs channel we're going to need our auth in point we're going to need our host we're gonna need our port now inside our mounted method we wanna go ahead and initialize our apps variable so we're gonna set the value of that to equal the first app inside our variable apps or null all right now we're ready to work on our connect method so let's just close these screens and for the connect method let's erase this connection part all right so we're gonna use pusher so we're gonna initialize our new pusher variable and this is coming from the pusher package we imported the cdn if you guys remember right here so for the new pusher the first thing we want to do is specify our app name i'm just calling mine staging and in here we want to pass in some variables so the first variable we're going to declare is our host so let's initialize that we're going to also do one for our port and we wanna also set the wss port variable now we wanna also set our display or let's set our path first ws path and that's going to be coming from our app variable and we want to also disable stats set this to true and we're going to set our auth in point and we're going to add some headers to our auth request so we want to add let me just fix this headers we want to add our xcsrf token to prevent [Music] cross script forgery so csrf dash token and this is coming from we're going to use blade syntax and we want to also add our app id so we do that by writing x app id and this is coming from our app and the last thing we want to do is enable transports we want to add ws and let's also add flash now let's go ahead and handle our events so if we were connected or disconnected or there's an error or a state changed pressure provide us with events that we can use to handle those situations so the syntax is going to go like this we're going to use our pusher variable we're going to use the index something called connection and we're gonna bind a function to that so the first one will be state change and for now let's just do nothing so i'm just gonna make an empty function here and let's copy this and paste it three more times so we have an event for state change we have one for connected we have one for disconnected and we have one for error for the error i'm just going to change this to a variable because they provide us with a variable called event here and here let's use our state variable so right now let's work on these three quickly so for the connected if this is true then we're gonna set our connected variable to true and for the disconnected we're gonna set our connect variable to false and for the error we're gonna set r connect variable or let's just we had a i think an error variable we called it uh where is it form error set this to true all right now for the state go ahead and add the display to our user interface to show us what the current state is so i'm going to make a new variable here let's call it state and set this to no and inside this parameter here i'm going to and assign it this state value so this dot state is equal to and let's call this the states actually because it contains more than one let's say states and let's say current state now let's go ahead and add this display right under our let's just show you in the front and first we want to add it right under the connect button here so that was under the header and here let's add it right under the form so it's going to be a div and let's just leave it empty with no class and in here i'm going to add a p tag and the p tag will contain the state and let's check our front end now let's try to connect now if you see this error which is telling you that the apps variable that we declared and the apps variable that's coming from our level backend is not a string and we cannot assign it to a string so what we have to do is we're going to go back to our code and for the apps variable we're just going to run json decode on it so let's just change here let's remove the comma in the first bracket and add two explanation points at the beginning and at the end and then here we're going to write json in code and we're going to wrap our apps variable in here and let's give this a try now before we press connect i'm going to open my developer tools and let's go ahead and click connect so if you see here the request is pending it's taking too long this is eventually going to time out and not work if you click on one of these requests you see it says unavailable so if you click on one of these requests and go to the header you should see that it was connecting using wss it should be doing it with ws the reason why wss doesn't work is because we don't have it configured for our local environment we cannot use ip addresses for that you have to actually use real domain names so let's go back to our code and let's fix that so the first thing i want to point out is inside here disable status this is incorrect it should be stats so disable stats and we're going to add a new variable it's called force tls and we're going to set it to false and let's give this a try so now we are connected now there is just one more thing we need to fix so right now we're connected but we're not seeing our area where we can send our message so let's go back to our code and the reason is here we use the connect variable but we called ours connected so let's just fix this typo quickly so let's go ahead and give this a try let's just update the connected message here and in here in the state i'm just going to add this message so channel's current state is and the state so let's refresh the screen and you can see this looks a little better now before we can build the send event on our front end we will need to create the back end first so we will need to make a new api in point let's go back to our code editor and in here let's go to our routes file and we want to go to web.php so let's go ahead and just create a new api in point in here and it's going to be a post request and let's just call give the route to be chat slash send and we're gonna use the callback function to declare it so we're going to grab two things we will need the message so if we go back to our front end here we will need this message and we will need the name here so the message is going to be coming from the request import method and we're gonna say message and we're gonna give it a default value of null and let's do the same thing but for the name and let's give it a default value of anonymous all right so we're gonna also return the time so we're gonna grab the current time of now and we're gonna format this to utc all right and if let's add here a condition so if name is equal to null then we're going to initialize it with this value now the reason why i have to do it here as well is because if you were to not include name in your api request then it will initialize it here as anonymous but if you sent it with null value then this will actually be assigned to null so this is why we have to do the check here so once we grab the message we will need to create an in a new event and dispatch that and we will have our front end listen to this event and update our interface so to create a new event we're going to open up a code terminal and in here we're going to write php artisan make event and let's just call this send message now once that's done let's go ahead and go back to our code and your new event file should be inside your app you'll find here a new folder called events and you should see send meshes is right here so for this event i'm going to add three variables one for name and one for message and the other one for time and we will initialize these variables inside our constructor and we will initialize our local variables here let's just copy this all right so we will need to create a new method in here and let's say the method is going to be called broadcast with and in here we're going to return our variables but in an array format so we have our name we have our message and we have our time now for the channel we will need to uh create a new one for ourselves so here we're using the broadcast on so this is what it will where this event will be broadcasted and in here we're gonna have to create a new channel so let's erase this and let's go ahead and return new channel and let's call this channel send message let's call it send message event now to create this channel we're gonna go to our routes file and here we're gonna go to channels let's go ahead and erase all this and let's create our new channel so we're gonna have to write broadcast channel and ours was called the send message event and we're gonna have to declare a callback function here and let's just uh let me just remove the quotation from here and add it here and in here we're going to return our variables so the same thing that we did here let's just copy this now let's go back to our web.php file and we want to dispatch our new event so let's copy the send message here and to create a new event we simply want to write send message dispatch and in here in the parameters we want to pass in the same values that we set inside our constructor so name message and time now this event is going to be handled by rq so it's very important that you make sure that your uh your queue is running let's go ahead now and build our send event in our front end so we're gonna go to our chat dash app dash example blade file and let's scroll all the way down here we have our send message function so the first thing we want to do is we want to set the form error to false in here and let's quickly check if our message is equal to null or empty and this message is basically what we set for our input box and we have it i think inside our variable here so where is so we have message and we have name let me just group these together so name can be empty but message is required so if message is not valid we're going to set the form error to true else we're going to send our post request and we're going to be using jquery for this so our endpoint was let's go back to our web.php file it was a slash chat send and we're going to handle this so we're going to first give a few variables inside our header we're going to add the token and this is going to be our cs rf token we're going to also add our message and we're going to add our name all right now we're going to handle the case where if it failed there is no response we don't have we don't need to worry about the success case but if it failed we're just going to uh alert an error all right let's give this a try on our front end let's refresh let's connect and i'm going to open developer tools here and let's go ahead and send an event and we have an error here and it's saying undefined property date time let's go back to our web.php file and let's see what's happening here so so here i made the mistake and i was supposed to call this inside the format method all right let's go back to our terminal and let's send the event again and we can see that it worked to make sure that this is actually working we will need to check if our queue is actually sending the events so let's open the terminal where we had our queue running and you can see here there is no output so this isn't really working and let's double check why so let's go back to our event class send message and in here when we created this event class using the laravel terminal it did not create this class to implement the should broadcast feature so let's go ahead and add it here so we want to write implements should broadcast now let's go back to our website and let's try again and let's go back to our terminal and you can see here our apps send message is being processed so on our front end we will need to listen to this and we will need to display the event once it's sent now let's go back to our front-end code and we want to scroll up to the connect method and in here let's scroll all the way down and at the bottom let us create a new method and call it so let's call that method subscribe subscribe to all channels and let's go ahead and create this method so we're going to add it on the very first before the disconnect and in here we're just going to have an array and we're going to run it for each statement for it and inside the array we're going to add our channel name that we want to subscribe to so beyond code comes with one that's pre-built it's called api message let's connect that to that and let's go ahead and create another function and let's call it subscribe to channel and let's provide the channel name here let's go ahead and create this new function now here the first thing i want to do is create a new instance for this so let's do that here and let's call the pusher subscribe method so in here in the first two parameters we need to specify the log channel and we did not pass the parameter so we need to add channel here channel name and let's uh collapse this and we want to run the dot bind method in here we want to use the log message event and for this we will have a callback function and it will give us a variable data that's where we're gonna get our event data from so inside this function we're gonna have a check so we're going to say if the data type is equal to the api message event and inside the if statement if the data details includes so here we want to say if the if details which is a variable inside the object data includes our custom event here our channel name then we want to actually display this message to our ui so what we're going to do is we're going to say let message data equal so this is where we're gonna parse our message data so i recommend you guys run the console log here on data so let me just fix this here and you should be able to see what this actually looks like well i'm gonna just leave this commented out and let's go ahead and grab our time as well so let utc date equal to new date and we have the message data and let's uh grab time from there and let's convert it to the user current time i think it's a two local string all right and let's go back to the top here scroll up and it recalled ours incoming message so we wanna just remove this and let's go ahead and push this into here so we're gonna use our instance variable here the inst we're calling our incoming messages we're gonna push our values in here so we're gonna push the message data now let's uh let's go ahead and give this a try let's see if it's working on our front end let's refresh the page let's connect and let's send an event and you can see it's working um i'm just going to change the send event to send message so in here let's find send event and this is our button here let's send it to let's change it to send message and let's refresh and yeah that's pretty much it i hope you guys uh like this tutorial if you found this tutorial useful i would greatly appreciate it if you guys hit that like button and if you have any questions yeah leave it in the comment below we'll see you on the next tutorial
Info
Channel: Emad Zaamout
Views: 8,693
Rating: undefined out of 5
Keywords:
Id: qdhnC_FUBbs
Channel Id: undefined
Length: 75min 40sec (4540 seconds)
Published: Sun May 01 2022
Related Videos
Note
Please note that this website is currently a work in progress! Lots of interesting data and statistics to come.