Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

stratboy's avatar

Best approach to build a live chat with Laravel

Hi, I'm quite new to this kind of projects. I want to build a live chat for a seed savers non profit website, which can be used by users to contact each other and ask for heirloom seeds to exchange.

First of all, it's not clear to me if Laravel already has a websocket server. On the docs they suggest some commercial websocket projects, and a couple of 'almost free' ones, but to me they do not seem viable solutions. If I really need to use websockets, I would go with socket.io, and try to use it with Laravel. Still:

  • Not sure if I really need websocket
  • Not sure if Laravel already has a built-in websocket server
  • Not sure if I could use socket.io
  • If I use socket.io, what's the best way to intergrate with Laravel

Could someone please point me to the right direction?

0 likes
22 replies
LaryAI's avatar
Level 58

Laravel does not come with a built-in WebSocket server, but it does provide an event broadcasting system that works well with WebSockets. You can use various WebSocket server implementations with Laravel, such as Laravel WebSockets, which is a package that allows you to set up a WebSocket server in Laravel without needing to use a third-party service.

Here's a step-by-step guide to setting up a live chat using Laravel and Laravel WebSockets:

  1. Install Laravel WebSockets: First, you need to install the beyondcode/laravel-websockets package via Composer.

    composer require beyondcode/laravel-websockets
    
  2. Publish the Configuration File: After installing the package, publish the configuration file.

    php artisan vendor:publish --provider="BeyondCode\LaravelWebSockets\WebSocketsServiceProvider" --tag="migrations"
    php artisan vendor:publish --provider="BeyondCode\LaravelWebSockets\WebSocketsServiceProvider" --tag="config"
    
  3. Run the Migrations: Run the migrations to create the necessary tables.

    php artisan migrate
    
  4. Configure .env: Set up your .env file with the appropriate settings for your WebSocket server.

    PUSHER_APP_ID=your-app-id
    PUSHER_APP_KEY=your-app-key
    PUSHER_APP_SECRET=your-app-secret
    PUSHER_APP_CLUSTER=mt1
    
    BROADCAST_DRIVER=pusher
    
    PUSHER_APP_HOST=127.0.0.1
    PUSHER_APP_PORT=6001
    PUSHER_APP_SCHEME=http
    
  5. Configure broadcasting.php: In your config/broadcasting.php file, make sure to configure the pusher broadcaster to use the local WebSocket server.

    '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'),
            'useTLS' => false,
            'host' => env('PUSHER_APP_HOST'),
            'port' => env('PUSHER_APP_PORT'),
            'scheme' => env('PUSHER_APP_SCHEME'),
        ],
    ],
    
  6. Start the WebSocket Server: You can start the WebSocket server by running the following command:

    php artisan websockets:serve
    
  7. Set Up Event Broadcasting: Create an event in Laravel that will be broadcasted over the WebSocket channel.

    use Illuminate\Broadcasting\Channel;
    use Illuminate\Queue\SerializesModels;
    use Illuminate\Broadcasting\PrivateChannel;
    use Illuminate\Broadcasting\PresenceChannel;
    use Illuminate\Foundation\Events\Dispatchable;
    use Illuminate\Broadcasting\InteractsWithSockets;
    use Illuminate\Contracts\Broadcasting\ShouldBroadcast;
    
    class MessageSent implements ShouldBroadcast
    {
        use Dispatchable, InteractsWithSockets, SerializesModels;
    
        public $message;
    
        public function __construct($message)
        {
            $this->message = $message;
        }
    
        public function broadcastOn()
        {
            return new PrivateChannel('chat');
        }
    }
    
  8. Listen for Events on the Client Side: On the client side, you can use Laravel Echo to listen for events. You'll need to install laravel-echo and pusher-js via npm or yarn.

    npm install --save laravel-echo pusher-js
    

    Then, in your JavaScript, configure Echo to use your WebSocket server.

    import Echo from 'laravel-echo';
    
    window.Pusher = require('pusher-js');
    
    window.Echo = new Echo({
        broadcaster: 'pusher',
        key: 'your-app-key',
        wsHost: window.location.hostname,
        wsPort: 6001,
        disableStats: true,
        encrypted: false
    });
    
    Echo.private('chat')
        .listen('MessageSent', (e) => {
            console.log(e.message);
        });
    
  9. Build the Chat Interface: Create the necessary frontend components to send and display messages.

  10. Handle Sending Messages: When a user sends a message, dispatch the MessageSent event.

    broadcast(new MessageSent($message))->toOthers();
    

This is a basic outline to get you started with building a live chat feature using Laravel and WebSockets. You'll need to customize the chat system to fit your specific needs, handle authentication, and ensure that users can only listen to channels they're allowed to.

1 like
stratboy's avatar

@LaryAI not only laravel-websocket is a 3rd party sowtware, but it's also a dead project, therefore not a good choice.

How would I do with socket.io + laravel?

martinbean's avatar

@stratboy laravel-websockets is not “dead”. Lary also won’t reply:

This reply was automagically generated by our local A.I. Think of it as a one-off attempt to instantly solve your problem. It will not respond to further replies.

jlrdw's avatar

I searched for tutorials on this, there seem to be quite a few.

Edit:

The chat video from @jeffreyway wasn't enough to get you started?

stratboy's avatar

@jlrdw Hi, you're right, that video could help, I'm watching it. It's quite old (2015) but core concepts seem to be similar. The only thing is, in 2015 I think Laravel didn't have all the broadcasting capabilities it now has, and also, it's not clear which drivers are now available, since official docs, on the same article, tell about Pusher Channels and Redis (https://laravel.com/docs/10.x/broadcasting#configuration), but then they instead tell Pusher Channels and Ably (https://laravel.com/docs/10.x/broadcasting#supported-drivers). Jeffrey uses a Redis driver, which now it's not clear if it's available. Also, Laravel Echo seemed not to exist in 2015, therefore, should I now use it or not and, what exacly should be its role in this game, if compared to the code explained in Jeffrey's video?

jlrdw's avatar

@stratboy he mentioned in the video that they also had a tutorial, see if their latest version has an up-to-date tutorial.

stratboy's avatar

Ok the answer here is: if you have a commercial project go with Pusher or Ably, because not only they're basically the only tools Laravel currently actively support and document, but also because the 'free' alternatives are not up to date and actively developed:

  • laravel-echo-server (Socket.io server side) supports only socket.io v 2.3.0, and is not actively developed
  • laravel-websockets (php) is not actively developed

If you're not doing a commercial project, probably the better solution is Sokety (js), which is almost actively supported and at least has paid support, if needed. Sokety uses uWebSockets.js instead of Socket.io.

Armghan's avatar
Armghan
Best Answer
Level 1

I'm currently working on something like. I tried and have technically succeeded in making a Livewire based chat widget for my site. But obviously polling is the worse method for doing this so I'm getting into Broadcasting.

It's a little difficult for newbie.

If you've succeeded in making this. May I please have any suggestion of tutorial you ended up using?

1 like
stratboy's avatar

@Armghan Hi, no sorry I ended up with polling too, simply because the kind of interaction between users in my project, in the end doesn't really require real time. It's unlikely it would happen. Anyway, if you really need real time and do not wnt to go with the commercial projects, my suggestion is to find a good tut about Sokety js. I think this is the best solution right now.

1 like
Armghan's avatar

@stratboy Appreciate the reply... I figured out how to setup broadcasting. I've successfully implemented Pusher Sockets. Works like a charm.

Also, I've setup DB Queue and a spatie Short-schedule for a command which checks every 5 secs for all active members to show at back end. And a queued loop on front end at every 5 secs for updating last active.

So far I've tested with 20 users at the same time and it seems to be solid realtime perk. Haha

1 like
stratboy's avatar

@Armghan Great, but Pusher Sockets maybe is commercial? I mean, are you spending some money to keep the app active?

Armghan's avatar

@stratboy Nah it's free for a 100 channels and like 200k messages per day....

I did the math and I could get about 80 csts per time (I usually, at max, get a 1k csts per day and VERY RARELY at most 20 at a time...)

Infact there's another Socket provider Ably, they have 600k msgs... If I feel like updating, I'll just move to another free one... hehe ;)

1 like
Merklin's avatar

I think the pool is not the best solution. When pool is active, it rerenders the component. What happens if the 'pool' is triggered while a user is typing? Everything he wrote will be lost. So:

  1. Either put the form for the new message on a separate livewire component
  2. Use broadcasting to update the messages
Merklin's avatar

@stratboy You said it yourself that you ended up using pooling a couple of posts above. ")

stratboy's avatar

@Merklin polling, not pooling :) Anyway, not using broadcasting, nor livewire. Just little js. No probs here. Thank you anyway for your suggestions.

1 like
jaseofspades88's avatar

One can only assume 'pool' is supposed to mean 'poll'. From experience polling gives enough of the illusion of real-time that an otherwise over engineered sockets implementation would give you. The comment about rendering the component isn't really an issue either as that's the whole point of something like Livewire.

stratboy's avatar

@jaseofspades88 yes, I think it really depends on what it's really needed. Realtime is not polling. But often a chat can be 'polling'. A chat used like a messaging app on a website, will rarely exploit real realtime, so polling can be more than enough in that case. A tech support chat maybe can be a more appropriate candidate for websockets and realtime. But the projects where really websockets are needed, are more things related to gaming, financial, medical, performance, etc..

mrshk's avatar

In my current project, the previous developer built a chat system using Node.js and Socket.io. Now, I’m facing issues whenever the client requests a new feature—especially when it comes to sending role-based notifications.

If you guys could suggest the best way to approach this, I’d really appreciate it.

Please or to participate in this conversation.