Table of Contents
Broadcast Configuration File
Create an Event Class
How to Test Our Setup
Conclusion
Home Backend Development PHP Tutorial How Laravel Broadcasting Works

How Laravel Broadcasting Works

Mar 05, 2025 am 09:27 AM

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>
Copy after login
Copy after login
Copy after login

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>
Copy after login
Copy after login
Copy after login

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>
Copy after login

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>
Copy after login
Copy after login
Copy after login

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>
Copy after login
Copy after login
Copy after login

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>
Copy after login
Copy after login
Copy after login

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>
Copy after login
Copy after login
Copy after login

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 of this Website
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

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

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Explain JSON Web Tokens (JWT) and their use case in PHP APIs. Explain JSON Web Tokens (JWT) and their use case in PHP APIs. Apr 05, 2025 am 12:04 AM

JWT is an open standard based on JSON, used to securely transmit information between parties, mainly for identity authentication and information exchange. 1. JWT consists of three parts: Header, Payload and Signature. 2. The working principle of JWT includes three steps: generating JWT, verifying JWT and parsing Payload. 3. When using JWT for authentication in PHP, JWT can be generated and verified, and user role and permission information can be included in advanced usage. 4. Common errors include signature verification failure, token expiration, and payload oversized. Debugging skills include using debugging tools and logging. 5. Performance optimization and best practices include using appropriate signature algorithms, setting validity periods reasonably,

What are Enumerations (Enums) in PHP 8.1? What are Enumerations (Enums) in PHP 8.1? Apr 03, 2025 am 12:05 AM

The enumeration function in PHP8.1 enhances the clarity and type safety of the code by defining named constants. 1) Enumerations can be integers, strings or objects, improving code readability and type safety. 2) Enumeration is based on class and supports object-oriented features such as traversal and reflection. 3) Enumeration can be used for comparison and assignment to ensure type safety. 4) Enumeration supports adding methods to implement complex logic. 5) Strict type checking and error handling can avoid common errors. 6) Enumeration reduces magic value and improves maintainability, but pay attention to performance optimization.

How does session hijacking work and how can you mitigate it in PHP? How does session hijacking work and how can you mitigate it in PHP? Apr 06, 2025 am 12:02 AM

Session hijacking can be achieved through the following steps: 1. Obtain the session ID, 2. Use the session ID, 3. Keep the session active. The methods to prevent session hijacking in PHP include: 1. Use the session_regenerate_id() function to regenerate the session ID, 2. Store session data through the database, 3. Ensure that all session data is transmitted through HTTPS.

Describe the SOLID principles and how they apply to PHP development. Describe the SOLID principles and how they apply to PHP development. Apr 03, 2025 am 12:04 AM

The application of SOLID principle in PHP development includes: 1. Single responsibility principle (SRP): Each class is responsible for only one function. 2. Open and close principle (OCP): Changes are achieved through extension rather than modification. 3. Lisch's Substitution Principle (LSP): Subclasses can replace base classes without affecting program accuracy. 4. Interface isolation principle (ISP): Use fine-grained interfaces to avoid dependencies and unused methods. 5. Dependency inversion principle (DIP): High and low-level modules rely on abstraction and are implemented through dependency injection.

Explain late static binding in PHP (static::). Explain late static binding in PHP (static::). Apr 03, 2025 am 12:04 AM

Static binding (static::) implements late static binding (LSB) in PHP, allowing calling classes to be referenced in static contexts rather than defining classes. 1) The parsing process is performed at runtime, 2) Look up the call class in the inheritance relationship, 3) It may bring performance overhead.

What is REST API design principles? What is REST API design principles? Apr 04, 2025 am 12:01 AM

RESTAPI design principles include resource definition, URI design, HTTP method usage, status code usage, version control, and HATEOAS. 1. Resources should be represented by nouns and maintained at a hierarchy. 2. HTTP methods should conform to their semantics, such as GET is used to obtain resources. 3. The status code should be used correctly, such as 404 means that the resource does not exist. 4. Version control can be implemented through URI or header. 5. HATEOAS boots client operations through links in response.

How do you handle exceptions effectively in PHP (try, catch, finally, throw)? How do you handle exceptions effectively in PHP (try, catch, finally, throw)? Apr 05, 2025 am 12:03 AM

In PHP, exception handling is achieved through the try, catch, finally, and throw keywords. 1) The try block surrounds the code that may throw exceptions; 2) The catch block handles exceptions; 3) Finally block ensures that the code is always executed; 4) throw is used to manually throw exceptions. These mechanisms help improve the robustness and maintainability of your code.

What are anonymous classes in PHP and when might you use them? What are anonymous classes in PHP and when might you use them? Apr 04, 2025 am 12:02 AM

The main function of anonymous classes in PHP is to create one-time objects. 1. Anonymous classes allow classes without names to be directly defined in the code, which is suitable for temporary requirements. 2. They can inherit classes or implement interfaces to increase flexibility. 3. Pay attention to performance and code readability when using it, and avoid repeatedly defining the same anonymous classes.

See all articles