Home Arrow Icon Knowledge base Arrow Icon Global Arrow Icon Laravel Soketi example


Laravel Soketi example


Here's a concise example of how to use Soketi with Laravel for real-time communication:

Setting up Soketi

1. Install Soketi globally using npm:


npm install -g @soketi/soketi

2. Start the Soketi server:


soketi start

Configuring Laravel

1. Install the required packages:


composer require pusher/pusher-php-server

2. Update the `.env` file with the Soketi connection details:


BROADCAST_DRIVER=pusher
PUSHER_APP_ID=app-id
PUSHER_APP_KEY=app-key
PUSHER_APP_SECRET=app-secret
PUSHER_HOST=127.0.0.1
PUSHER_PORT=6001
PUSHER_SCHEME=http

3. Uncomment the `BroadcastServiceProvider` in your `config/app.php` file.

Broadcasting Events

1. Create a new event class:


php artisan make:event NewMessageEvent

2. In the `NewMessageEvent` class, define the event payload:

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

    public $message;

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

    public function broadcastOn()
    {
        return new PrivateChannel('chat-room');
    }
}

3. Dispatch the event when a new message is created:

php
event(new NewMessageEvent($newMessage));

Listening for Events on the Frontend

1. Install Laravel Echo and Pusher JS:


npm install --save-dev laravel-echo pusher-js

2. Configure Laravel Echo in your `resources/js/bootstrap.js` file:

js
import Echo from 'laravel-echo';

window.Pusher = require('pusher-js');

window.Echo = new Echo({
    broadcaster: 'pusher',
    key: process.env.MIX_PUSHER_APP_KEY,
    cluster: process.env.MIX_PUSHER_CLUSTER,
    forceTLS: false,
    wsHost: window.location.hostname,
    wsPort: 6001,
});

3. Subscribe to the event in your Vue component:

js
mounted() {
    window.Echo.private('chat-room')
        .listen('NewMessageEvent', (e) => {
            this.messages.push(e.message);
        });
}

This example demonstrates how to set up Soketi, configure Laravel to use it for broadcasting, create a custom event, and listen for the event on the frontend using Laravel Echo. The key aspects are the Soketi server setup, the Pusher-compatible environment variables, and the integration of Laravel Echo for the frontend.

Citations:
[1] https://fajarwz.com/blog/unlocking-real-time-with-websockets-in-laravel-with-soketi/
[2] https://github.com/fajarwz/blog-laravel-soketi
[3] https://serhii.io/posts/soketi-free-laravel-web-sockets-with-docker
[4] https://github.com/soketi/laravel-chat-app
[5] https://kbouzidi.com/real-time-events-with-laravel-and-soketi