Google+
Shineyrock web design & consultancy

Shineyrock

blog

  • like 5 06

    How Laravel Broadcasting Works

    Today, we are going to explore the concept of broadcasting in the Laravel web framework. It allows you to send notifications to the client side when something happens on the server side. In this article, we are going to use the third-party Pusher library to send notifications to the client side.

    If you have ever wanted to send notifications from the server to the client when something happens on a server in Laravel, you're looking for the broadcasting feature.

    For example, let's assume that you've implemented a messaging application that allows users of your system to send messages to each other. Now, when user A sends a message to user B, you want to notify user B in real time. You may display a popup or an alert box that informs user B about the new message!

    It's the perfect use-case to walk through the concept of broadcasting in Laravel, and that's what we'll implement in this article.

    If you are wondering how the server could send notifications to the client, it's using sockets under the hood to accomplish it. Let's understand the basic flow of sockets before we dive deeper into the actual implementation.

    • Firstly, you need a server which supports the web-sockets protocol and allows the client to establish a web socket connection.
    • You could implement your own server or use a third-party service like Pusher. We'll prefer the latter in this article.
    • The client initiates a web socket connection to the web socket server and receives a unique identifier upon successful connection.
    • Once the connection is successful, the client subscribes to certain channels at which it would like to receive events.
    • Finally, under the subscribed channel, the client registers events that it would like to listen to.
    • Now on the server side, when a particular event happens, we inform the web-socket server by providing it with the channel name and event name.
    • And finally, the web-socket server broadcasts that event to registered clients on that particular channel.

    Don't worry if it looks like too much in a single go; you will get the hang of it as we move through this article.

    Broadcast Configuration File

    Next, let's have a look at the default broadcast configuration file at config/broadcasting.php.

    By default, Laravel supports multiple broadcast adapters in the core itself.

    In this article, we are going to use the pusher broadcast adapter. For debugging purposes, you could also use the log adapter. Of course, if you're using the log adapter, the client won't receive any event notifications, and it'll only be logged to the laravel.log file.

    From the next section onward, we'll right away dive into the actual implementation of the aforementioned use-case.

    Setting Up the Prerequisites

    In broadcasting, there are different types of channels—public, private, and presence. When you want to broadcast your events publicly, it's the public channel that you are supposed to use. Conversely, the private channel is used when you want to restrict event notifications to certain private channels.

    In our use-case, we want to notify users when they get a new message. And to be eligible to receive broadcast notifications, the user must be logged in. Thus, we'll need to use the private channel in our case.

    Core Authentication Feature

    Firstly, you need to enable the default Laravel authentication system so that features like registration, login and the like work out of the box. If you're not sure how to do that, the official documentation provides a quick insight into that.

    Pusher SDK: Installation and Configuration

    As we're going to use the Pusher third-party service as our web-socket server, you need to create an account with it and make sure you have the necessary API credentials with your post registration.

    Next, we need to install the Pusher PHP SDK so that our Laravel application can send broadcast notifications to the Pusher web-socket server.

    In your Laravel application root, run the following command to install it as a composer package.

    Now, let's change the .env file to enable the pusher adapter as our default broadcast driver.

    As you can see, we've changed the default broadcast driver to pusher. You also need to configure other options that you should have got from the Pusher account in the first place.

    Finally, let's enable the broadcast service in config/app.php by removing the comment in the following line.

    So far, we've installed server-specific libraries. In the next section, we'll go through client libraries that need to be installed as well.

    Pusher and Laravel Echo Libraries—Installation and Configuration

    In broadcasting, the responsibility of the client side is to subscribe to channels and listen for desired events. Under the hood, it accomplishes it by opening a new connection to the web-socket server.

    Luckily, we don't have to implement any complex JavaScript stuff to achieve it as Laravel already provides a useful client library, Laravel Echo, which helps us to deal with sockets on the client side. Also, it supports the Pusher service that we're going to use in this article.

    You can install the Laravel Echo library by using the NPM package manager. Of course, you need to install Node and npm if you don't have them already. The rest is pretty simple, as shown in the following snippet.

    What we're interested in is the node_modules/laravel-echo/dist/echo.js file that you should copy to public/echo.js.

    And with that, we're done with the setup of our client libraries.

    Back-End File Setup

    Recall that we were talking about setting up an application which allows users of our application to send messages to each other. On the other hand, we'll send broadcast notifications to users that are logged in when they receive a new message from other users.

    In this section, we'll create the files that are required in order to implement the use-case that we're looking for.

    Create a Model Class

    To start with, let's create the Message model which holds the messages that users send to each other.

    We also need to add a few fields like to, from, and message to our messages table. So let's change the migration file database/migrations/XXXX_XX_XX_XXXXXX_create_messages_table.php before running the migrate command.

    Now, let's run the migrate command, which creates the messages table in the database.

    Create an Event Class

    Whenever you want to raise a custom event in Laravel, you should create a class for that event. Based on the type of event, Laravel reacts accordingly and takes the necessary actions.

    If the event is a normal event, Laravel calls the associated listener classes. On the other hand, if the event is of the broadcast type, Laravel sends that event to the web-socket server which is configured in the config/broadcasting.php file.

    As we're using the Pusher service in our example, Laravel will send events to the Pusher server.

    Let's use the following artisan command to create a custom event class: NewMessageNotification.

    That should create the app/Events/NewMessageNotification.php file. Let's replace the contents of that file with the following.

    The important thing to note is that the NewMessageNotification class implements the ShouldBroadcastNow interface. Thus, when we raise an event, Laravel knows that this event should be broadcast.

    In fact, you could also implement the ShouldBroadcast interface, and Laravel adds an event into the event queue. It'll be processed by the event queue worker when it gets a chance to do so. In our case, we want to broadcast it right away, and that's why we've used the ShouldBroadcastNow interface.

    In our case, we want to display a message the user has received, and thus we've passed the Message model in the constructor argument. In this way, the data will be passed along with the event.

    Next, there is the broadcastOn method, which defines the name of the channel on which the event will be broadcast. In our case, we've used the private channel as we want to restrict the event broadcast to logged-in users.

    The $this->message->to variable refers to the ID of the user to which the event will be broadcast. Thus, it effectively makes the channel name like user.{USER_ID}.

    Create Broadcast Routes

    In the case of private channels, the client must authenticate itself before establishing a connection with the web-socket server. It makes sure that events that are broadcast on private channels are sent to authenticated clients only. In our case, it means that only logged-in users will be able to subscribe to our channel user.{USER_ID}.

    If you're using the Laravel Echo client library for channel subscription, you're in luck! It automatically takes care of the authentication part, and you just need to define the channel routes.

    Let's go ahead and add a route for our private channel in the routes/channels.php file.

    As you can see, we've defined the user.{toUserId} route for our private channel.

    The second argument of the channel method should be a closure function. Laravel automatically passes the currently logged-in user as the first argument of the closure function, and the second argument is usually fetched from the channel name.

    When the client tries to subscribe to the private channel user.{USER_ID}, the Laravel Echo library does the necessary authentication in the background using the XMLHttpRequest object, more commonly known as XHR.

    We've now finished the setup, so let's go ahead and test it.

    Front-End File Setup

    In this section, we'll create the files that are required to test our use-case.

    Create a Controller

    Let's go ahead and create a controller file at app/Http/Controllers/MessageController.php with the following contents.

    Create a View

    In the index method, we're using the broadcast view, so let's create the resources/views/broadcast.blade.php view file as well.

    Add Routes

    Finally, we need to add routes as well in the routes/web.php file.

    How It Works Altogether

    In the constructor method of the controller class, you can see that we've used the auth middleware to make sure that controller methods are only accessed by logged-in users.

    Next, there's the index method, which renders the broadcast view. Let's pull in the most important code in the view file.

    Firstly, we load the necessary client libraries, Laravel Echo and Pusher, allowing us to open the web-socket connection to the Pusher web-socket server.

    Next, we create the instance of Echo by providing pusher as our broadcast adapter and other necessary pusher-related information.

    Moving further, we use the private method of Echo to subscribe to the private channel user.{USER_ID}. As we discussed earlier, the client must authenticate itself before subscribing to the private channel. Thus the Echo object performs the necessary authentication by sending the XHR in the background with the necessary parameters. Finally, Laravel tries to find the user.{USER_ID} route, and it should match the route that we've defined in the routes/channels.php file.

    If everything goes fine, you should have a web-socket connection open with the Pusher web-socket server, and it's listing events on the user.{USER_ID} channel! From now on, we'll be able to receive all incoming events on this channel.

    In our case, we want to listen for the NewMessageNotification event, and thus we've used the listen method of the Echo object to achieve it. To keep things simple, we'll just alert the message that we've received from the Pusher server.

    So that was the setup for receiving events from the web-sockets server. Next, we'll go through the send method in the controller file that raises the broadcast event.

    Let's quickly pull in the code of the send method.

    In our case, we're going to notify logged-in users when they receive a new message. So we've tried to mimic that behavior in the send method.

    Next, we've used the event helper function to raise the NewMessageNotification event. Since the NewMessageNotification event is of ShouldBroadcastNow type, Laravel loads the default broadcast configuration from the config/broadcasting.php file. Finally, it broadcasts the NewMessageNotification event to the configured web-socket server on the user.{USER_ID} channel.

    In our case, the event will be broadcast to the Pusher web-socket server on the user.{USER_ID} channel. If the ID of the recipient user is 1, the event will be broadcast over the user.1 channel.

    As we discussed earlier, we already have a setup that listens to events on this channel, so it should be able to receive this event, and the alert box is displayed to the user!

    How to Test Our Setup

    Let's go ahead and walk through how you are supposed to test the use-case that we've built so far.

    Open the URL https://your-laravel-site-domain/message/index in your browser. If you're not logged in yet, you'll be redirected to the login screen. Once you're logged in, you should see the broadcast view that we defined earlier—nothing fancy yet.

    In fact, Laravel has done quite a bit of work in the background already for you. As we've enabled the Pusher.logToConsole setting provided by the Pusher client library, it logs everything in the browser console for debugging purposes. Let's see what's being logged to the console when you access the http://your-laravel-site-domain/message/index page.

    It has opened the web-socket connection with the Pusher web-socket server and subscribed itself to listen to events on the private channel. Of course, you could have a different channel name in your case based on the ID of the user that you're logged in with. Now, let's keep this page open as we move to test the send method.

    Next, let's open the http://your-laravel-site-domain/message/send URL in the other tab or in a different browser. If you're going to use a different browser, you need to log in to be able to access that page.

    As soon as you open the http://your-laravel-site-domain/message/send page, you should be able to see an alert message in the other tab at http://your-laravel-site-domain/message/index.

    Let's navigate to the console to see what has just happened.

    As you can see, it tells you that you've just received the App\Events\NewMessageNotification event from the Pusher web-socket server on the private-user.2 channel.

    In fact, you can see what's happening out there at the Pusher end as well. Go to your Pusher account and navigate to your application. Under the Debug Console, you should be able to see messages being logged.

    debug consoledebug consoledebug console

    And that brings us to the end of this article! Hopefully, it wasn't too much in a single go as I've tried to simplify things to the best of my knowledge.

    Conclusion

    Today, we went through one of the least discussed features of Laravel—broadcasting. It allows you to send real-time notifications using web sockets. Throughout the course of this article, we built a real-world example that demonstrated the aforementioned concept.

    martijn broeders

    founder/ strategic creative at shineyrock web design & consultancy
    e-mail: .(JavaScript must be enabled to view this email address)
    phone: 434 210 0245

By - category

    By - date