Home Arrow Icon Knowledge base Arrow Icon Global Arrow Icon Laravel 11 broadcasting example code
    Laravel 11 event broadcasting Laravel Echo WebSockets broadcasting driver public channels private channels Laravel Reverb Pusher Channels Ably


Laravel 11 broadcasting example code


Here is a concise answer to your query, based on the search results:

Laravel's event broadcasting allows you to broadcast your server-side Laravel events to your client-side JavaScript application using a driver-based approach to WebSockets. The events may be easily consumed on the client-side using the Laravel Echo JavaScript package.[1]

Events are broadcast over "channels", which may be specified as public or private. Any visitor to your application may subscribe to a public channel without any authentication or authorization; however, in order to subscribe to a private channel, a user must be authenticated and authorized to listen on that channel.[1][2]

To get started with broadcasting in Laravel 11:

1. Configure the broadcasting driver in the `config/broadcasting.php` file. Laravel supports several drivers out of the box, including Laravel Reverb, Pusher Channels, and Ably.[1]
2. Define broadcast events in your application by creating a `Broadcast` event class and implementing the `broadcastOn()` method to specify the channel(s) the event should broadcast to.[1][2]
3. Broadcast the event using the `Broadcast::event()` method, either directly or by dispatching the event.[2][3]
4. On the client-side, use Laravel Echo to subscribe to the broadcast channels and listen for the events. You can listen for events on both public and private channels.[2]

Here's an example of broadcasting an event in Laravel 11:

php
// In your event class
class PostUpdated extends Broadcast
{
    public $post;

    public function __construct(Post $post)
    {
        $this->post = $post;
    }

    public function broadcastOn()
    {
        return new Channel('posts');
    }
}

// In your controller
public function update(Request $request, Post $post)
{
    $post->update($request->all());

    event(new PostUpdated($post));

    return response()->json($post);
}

And on the client-side using Laravel Echo:

javascript
Echo.channel('posts')
    .listen('PostUpdated', (e) => {
        console.log(`A new post was updated: ${e.post.message}`);
    });

This example demonstrates broadcasting a `PostUpdated` event on the `posts` channel, which can be listened to by the client-side application using Laravel Echo.[1][2][3]

Citations:
[1] https://laravel.com/docs/11.x/broadcasting
[2] https://www.youtube.com/watch?v=G8xIEejDyDY
[3] https://laravel-news.com/laravel-11-5-0
[4] https://laravel.com/docs/11.x/notifications
[5] https://github.com/laravel/bootcamp.laravel.com/blob/main/config/broadcasting.php