How to create event Broadcasting in laravel?

laravel-logo

Event broadcasting in Laravel allows you to broadcast events to various channels, such as Pusher, Redis, or a Laravel Echo server, and then listen for those events on the client-side using JavaScript frameworks like Vue.js, React, or plain JavaScript.

Read full article.

Step 1: Set up the Broadcasting Driver First, make sure you have set up the broadcasting driver in the config/broadcasting.php file. For this example, let’s assume you are using the Pusher driver.

'pusher' => [
    'driver' => 'pusher',
    'key' => env('PUSHER_APP_KEY'),
    'secret' => env('PUSHER_APP_SECRET'),
    'app_id' => env('PUSHER_APP_ID'),
    'options' => [
        'cluster' => env('PUSHER_APP_CLUSTER'),
        'encrypted' => true,
    ],
],

Step 2: Define the Event Generate an event class using the artisan command php artisan make:event NewMessageEvent. The generated event class will be placed in the app/Events directory.

namespace App\Events;

use Illuminate\Broadcasting\Channel;
use Illuminate\Broadcasting\InteractsWithSockets;
use Illuminate\Broadcasting\PresenceChannel;
use Illuminate\Broadcasting\PrivateChannel;
use Illuminate\Contracts\Broadcasting\ShouldBroadcast;
use Illuminate\Foundation\Events\Dispatchable;
use Illuminate\Queue\SerializesModels;

class NewMessageEvent implements ShouldBroadcast
{
    use Dispatchable, InteractsWithSockets, SerializesModels;

    public $message;

    /**
     * Create a new event instance.
     *
     * @param  string  $message
     * @return void
     */
    public function __construct($message)
    {
        $this->message = $message;
    }

    /**
     * Get the channels the event should broadcast on.
     *
     * @return \Illuminate\Broadcasting\Channel|array
     */
    public function broadcastOn()
    {
        return new Channel('chat');
    }
}

Step 3: Create the Event Listener Generate an event listener using the artisan command php artisan make:listener NewMessageListener --event=NewMessageEvent. The generated listener class will be placed in the app/Listeners directory.

namespace App\Listeners;

use App\Events\NewMessageEvent;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Queue\InteractsWithQueue;

class NewMessageListener implements ShouldQueue
{
    /**
     * Handle the event.
     *
     * @param  \App\Events\NewMessageEvent  $event
     * @return void
     */
    public function handle(NewMessageEvent $event)
    {
        // Handle the event logic here
    }
}

Step 4: Dispatch the Event Dispatch the event from your application logic or controller.

For example:

use App\Events\NewMessageEvent;

public function sendMessage(Request $request)
{
    // Logic to send the message
    
    $message = $request->input('message');
    
    event(new NewMessageEvent($message));
}

Step 5: Listen for the Event On the client-side, you can use Laravel Echo or other JavaScript libraries to listen for the broadcasted event. Here’s an example using Laravel Echo and Vue.js:

import Echo from 'laravel-echo';

window.Echo = new Echo({
    broadcaster: 'pusher',
    key: 'your-pusher-key',
    cluster: 'your-pusher-cluster',
    encrypted: true
});

Echo.channel('chat')
    .listen('.NewMessageEvent', (event) => {
        console.log('New message received:', event.message);
        // Handle the received message
    });

In this example, whenever the NewMessageEvent is dispatched, it will be broadcasted to the “chat” channel. The client-side JavaScript code will listen to the “chat” channel and handle the received message.

Note: Make sure you have properly configured your Pusher credentials and the necessary JavaScript dependencies installed for Laravel Echo.

This is a basic example of how to use Laravel’s event broadcasting feature. You can customize it based on your application’s requirements and explore more advanced features like presence channels, private channels, and event listeners to build real-time features in your Laravel application.