search
HomeBackend DevelopmentPHP TutorialHow 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.

<?php <br><br>return [<br><br>    /*<br>    |--------------------------------------------------------------------------<br>    | Default Broadcaster<br>    |--------------------------------------------------------------------------<br>    |<br>    | This option controls the default broadcaster that will be used by the<br>    | framework when an event needs to be broadcast. You may set this to<br>    | any of the connections defined in the "connections" array below.<br>    |<br>    | Supported: "pusher", "redis", "log", "null"<br>    |<br>    */<br><br>    'default' => env('BROADCAST_DRIVER', 'null'),<br><br>    /*<br>    |--------------------------------------------------------------------------<br>    | Broadcast Connections<br>    |--------------------------------------------------------------------------<br>    |<br>    | Here you may define all of the broadcast connections that will be used<br>    | to broadcast events to other systems or over websockets. Samples of<br>    | each available type of connection are provided inside this array.<br>    |<br>    */<br><br>    'connections' => [<br><br>        'pusher' => [<br>            'driver' => 'pusher',<br>            'key' => env('PUSHER_APP_KEY'),<br>            'secret' => env('PUSHER_APP_SECRET'),<br>            'app_id' => env('PUSHER_APP_ID'),<br>            'options' => [<br>                'cluster' => env('PUSHER_APP_CLUSTER'),<br>                'useTLS' => true,<br>            ],<br>        ],<br><br>        'redis' => [<br>            'driver' => 'redis',<br>            'connection' => 'default',<br>        ],<br><br>        'log' => [<br>            'driver' => 'log',<br>        ],<br><br>        'null' => [<br>            'driver' => 'null',<br>        ],<br><br>    ],<br><br>];<br>

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

In this article, we are going to use the log adapter. Of course, if you're using the pusher adapter as our default broadcast driver.

...<br>...<br>BROADCAST_DRIVER=pusher<br><br>PUSHER_APP_ID={YOUR_APP_ID}<br>PUSHER_APP_KEY={YOUR_APP_KEY}<br>PUSHER_APP_SECRET={YOUR_APP_SECRET}<br>PUSHER_APP_CLUSTER={YOUR_APP_CLUSTER}<br>...<br>...<br>

As you can see, we've changed the default broadcast driver to messages table. So let's change the migration file database/migrations/XXXX_XX_XX_XXXXXX_create_messages_table.php before running the migrate command.

<?php <br> <br>use Illuminate\Support\Facades\Schema;<br>use Illuminate\Database\Schema\Blueprint;<br>use Illuminate\Database\Migrations\Migration;<br> <br>class CreateMessagesTable extends Migration<br>{<br>    /**<br>     * Run the migrations.<br>     *<br>     * @return void<br>     */<br>    public function up()<br>    {<br>        Schema::create('messages', function (Blueprint $table) {<br>            $table->increments('id');<br>            $table->integer('from', FALSE, TRUE);<br>            $table->integer('to', FALSE, TRUE);<br>            $table->text('message');<br>            $table->timestamps();<br>        });<br>    }<br> <br>    /**<br>     * Reverse the migrations.<br>     *<br>     * @return void<br>     */<br>    public function down()<br>    {<br>        Schema::dropIfExists('messages');<br>    }<br>}<br>

Now, let's run the messages table in the database.

<?php <br><br>return [<br><br>    /*<br>    |--------------------------------------------------------------------------<br>    | Default Broadcaster<br>    |--------------------------------------------------------------------------<br>    |<br>    | This option controls the default broadcaster that will be used by the<br>    | framework when an event needs to be broadcast. You may set this to<br>    | any of the connections defined in the "connections" array below.<br>    |<br>    | Supported: "pusher", "redis", "log", "null"<br>    |<br>    */<br><br>    'default' => env('BROADCAST_DRIVER', 'null'),<br><br>    /*<br>    |--------------------------------------------------------------------------<br>    | Broadcast Connections<br>    |--------------------------------------------------------------------------<br>    |<br>    | Here you may define all of the broadcast connections that will be used<br>    | to broadcast events to other systems or over websockets. Samples of<br>    | each available type of connection are provided inside this array.<br>    |<br>    */<br><br>    'connections' => [<br><br>        'pusher' => [<br>            'driver' => 'pusher',<br>            'key' => env('PUSHER_APP_KEY'),<br>            'secret' => env('PUSHER_APP_SECRET'),<br>            'app_id' => env('PUSHER_APP_ID'),<br>            'options' => [<br>                'cluster' => env('PUSHER_APP_CLUSTER'),<br>                'useTLS' => true,<br>            ],<br>        ],<br><br>        'redis' => [<br>            'driver' => 'redis',<br>            'connection' => 'default',<br>        ],<br><br>        'log' => [<br>            'driver' => 'log',<br>        ],<br><br>        'null' => [<br>            'driver' => 'null',<br>        ],<br><br>    ],<br><br>];<br>

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: pusher as our broadcast adapter and other necessary pusher-related information.

Moving further, we use the private<code>private method of Echo to subscribe to the private channel user.{USER_ID}<code>user.{USER_ID}. As we discussed earlier, the client must authenticate itself before subscribing to the private channel. Thus the Echo<code>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}<code>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}<code>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<code>NewMessageNotification event, and thus we've used the listen<code>listen method of the Echo<code>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<code>send method in the controller file that raises the broadcast event.

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

...<br>...<br>BROADCAST_DRIVER=pusher<br><br>PUSHER_APP_ID={YOUR_APP_ID}<br>PUSHER_APP_KEY={YOUR_APP_KEY}<br>PUSHER_APP_SECRET={YOUR_APP_SECRET}<br>PUSHER_APP_CLUSTER={YOUR_APP_CLUSTER}<br>...<br>...<br>

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<code>send method.

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

<?php <br><br>return [<br><br>    /*<br>    |--------------------------------------------------------------------------<br>    | Default Broadcaster<br>    |--------------------------------------------------------------------------<br>    |<br>    | This option controls the default broadcaster that will be used by the<br>    | framework when an event needs to be broadcast. You may set this to<br>    | any of the connections defined in the "connections" array below.<br>    |<br>    | Supported: "pusher", "redis", "log", "null"<br>    |<br>    */<br><br>    'default' => env('BROADCAST_DRIVER', 'null'),<br><br>    /*<br>    |--------------------------------------------------------------------------<br>    | Broadcast Connections<br>    |--------------------------------------------------------------------------<br>    |<br>    | Here you may define all of the broadcast connections that will be used<br>    | to broadcast events to other systems or over websockets. Samples of<br>    | each available type of connection are provided inside this array.<br>    |<br>    */<br><br>    'connections' => [<br><br>        'pusher' => [<br>            'driver' => 'pusher',<br>            'key' => env('PUSHER_APP_KEY'),<br>            'secret' => env('PUSHER_APP_SECRET'),<br>            'app_id' => env('PUSHER_APP_ID'),<br>            'options' => [<br>                'cluster' => env('PUSHER_APP_CLUSTER'),<br>                'useTLS' => true,<br>            ],<br>        ],<br><br>        'redis' => [<br>            'driver' => 'redis',<br>            'connection' => 'default',<br>        ],<br><br>        'log' => [<br>            'driver' => 'log',<br>        ],<br><br>        'null' => [<br>            'driver' => 'null',<br>        ],<br><br>    ],<br><br>];<br>

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.

...<br>...<br>BROADCAST_DRIVER=pusher<br><br>PUSHER_APP_ID={YOUR_APP_ID}<br>PUSHER_APP_KEY={YOUR_APP_KEY}<br>PUSHER_APP_SECRET={YOUR_APP_SECRET}<br>PUSHER_APP_CLUSTER={YOUR_APP_CLUSTER}<br>...<br>...<br>

As you can see, it tells you that you've just received the AppEventsNewMessageNotification 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.

How Laravel Broadcasting Works

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.

The above is the detailed content of How Laravel Broadcasting Works. For more information, please follow other related articles on the PHP Chinese website!

Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
What is the difference between unset() and session_destroy()?What is the difference between unset() and session_destroy()?May 04, 2025 am 12:19 AM

Thedifferencebetweenunset()andsession_destroy()isthatunset()clearsspecificsessionvariableswhilekeepingthesessionactive,whereassession_destroy()terminatestheentiresession.1)Useunset()toremovespecificsessionvariableswithoutaffectingthesession'soveralls

What is sticky sessions (session affinity) in the context of load balancing?What is sticky sessions (session affinity) in the context of load balancing?May 04, 2025 am 12:16 AM

Stickysessionsensureuserrequestsareroutedtothesameserverforsessiondataconsistency.1)SessionIdentificationassignsuserstoserversusingcookiesorURLmodifications.2)ConsistentRoutingdirectssubsequentrequeststothesameserver.3)LoadBalancingdistributesnewuser

What are the different session save handlers available in PHP?What are the different session save handlers available in PHP?May 04, 2025 am 12:14 AM

PHPoffersvarioussessionsavehandlers:1)Files:Default,simplebutmaybottleneckonhigh-trafficsites.2)Memcached:High-performance,idealforspeed-criticalapplications.3)Redis:SimilartoMemcached,withaddedpersistence.4)Databases:Offerscontrol,usefulforintegrati

What is a session in PHP, and why are they used?What is a session in PHP, and why are they used?May 04, 2025 am 12:12 AM

Session in PHP is a mechanism for saving user data on the server side to maintain state between multiple requests. Specifically, 1) the session is started by the session_start() function, and data is stored and read through the $_SESSION super global array; 2) the session data is stored in the server's temporary files by default, but can be optimized through database or memory storage; 3) the session can be used to realize user login status tracking and shopping cart management functions; 4) Pay attention to the secure transmission and performance optimization of the session to ensure the security and efficiency of the application.

Explain the lifecycle of a PHP session.Explain the lifecycle of a PHP session.May 04, 2025 am 12:04 AM

PHPsessionsstartwithsession_start(),whichgeneratesauniqueIDandcreatesaserverfile;theypersistacrossrequestsandcanbemanuallyendedwithsession_destroy().1)Sessionsbeginwhensession_start()iscalled,creatingauniqueIDandserverfile.2)Theycontinueasdataisloade

What is the difference between absolute and idle session timeouts?What is the difference between absolute and idle session timeouts?May 03, 2025 am 12:21 AM

Absolute session timeout starts at the time of session creation, while an idle session timeout starts at the time of user's no operation. Absolute session timeout is suitable for scenarios where strict control of the session life cycle is required, such as financial applications; idle session timeout is suitable for applications that want users to keep their session active for a long time, such as social media.

What steps would you take if sessions aren't working on your server?What steps would you take if sessions aren't working on your server?May 03, 2025 am 12:19 AM

The server session failure can be solved through the following steps: 1. Check the server configuration to ensure that the session is set correctly. 2. Verify client cookies, confirm that the browser supports it and send it correctly. 3. Check session storage services, such as Redis, to ensure that they are running normally. 4. Review the application code to ensure the correct session logic. Through these steps, conversation problems can be effectively diagnosed and repaired and user experience can be improved.

What is the significance of the session_start() function?What is the significance of the session_start() function?May 03, 2025 am 12:18 AM

session_start()iscrucialinPHPformanagingusersessions.1)Itinitiatesanewsessionifnoneexists,2)resumesanexistingsession,and3)setsasessioncookieforcontinuityacrossrequests,enablingapplicationslikeuserauthenticationandpersonalizedcontent.

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Atom editor mac version download

Atom editor mac version download

The most popular open source editor

DVWA

DVWA

Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software

SublimeText3 Linux new version

SublimeText3 Linux new version

SublimeText3 Linux latest version

EditPlus Chinese cracked version

EditPlus Chinese cracked version

Small size, syntax highlighting, does not support code prompt function

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor