Laravel web sockets

Getting started with Laravel Websockets can be hectic and boring for some people, me included. I went through several tutorials before I got it right. I wish to share my journey with you on how to integrate Websockets into a laravel application with you.  We’re going to use a free package by Marcel Pociot and Sebastian Schlein.

Lets get started by listing its prons:

  1. Ease of use. With Laravel Websockets, you do not need any additional software to start your own WebSocket server. Forget about Node – use the power of PHP.
  2. Laravel WebSockets has built-in Laravel Echo support out of the box and you can use it right away as a drop-in local Pusher replacement.
  3. Performance. This package is battle-tested in real-world applications and can serve high traffic websites easily.

  4. Multitenancy. This package comes with multi-tenancy support out of the box. his means that you could host it independently from your current Laravel application and serve multiple WebSocket applications with one server. (This is what we’ll use in this tutorial. I have created and hosted Websocker server on a VM)

Follow along to test how it works before we go through steps of creating and hosting one.

Step 1. Create a new Laravel Application

This can be easily done via composer.

Step 2. Install Laravel Websockets package

Step 3. Update broadcasting.php file. (config/broadcasting.php)

  • Go to broadcasting.php under  connections=>pusher update the port to point to our server as show below. Sample code.

Step 4. Install Laravel-echo.

Laravel Echo is a JavaScript library that makes it painless to subscribe to channels and listen for events broadcast by Laravel.

Step 5. Update bootstrap.js.

  • Update bootstrap.js to receive updates. Sample code.

Step 6. Update .env. (Replace below with pusher value and don’t forget to set pusher as your proffered broadcaster).

  • Replace .env pusher configuration with this configuration

Step 6. Run npm run watch

Step 7 Listen for Events.

Replace order OrderShipped with your event name. and e.order.name with your public variables in the event class. For more about this checkout Laravel events and Listeners

 

  • Thats all. We’re happy to hear from you via comments

2 thoughts on “Laravel web sockets

  1. admin says:

    Thanks for your comment. In this article, I used an hosted Web-socket server. I’ll do another article soon on how one can create own web-socket server that supports multi tenancy. One can use this article to test how web sockets works.

Leave a Reply

Your email address will not be published. Required fields are marked *