Real-Time Magic with Laravel WebSockets🚀

Shaon Majumder
3 min readFeb 9, 2024

--

Greetings, fellow adventurer of the digital realm! Welcome to a journey where the ordinary transforms into the extraordinary, and where the mystical forces of Laravel WebSockets bring real-time enchantment to life.

Prerequisites: Prepare Your Magical Arsenal✨

Before we embark on our journey, ensure you have your magical arsenal at hand:

  • PHP, the elixir of server-side sorcery
  • Composer, the enchanted scribe
  • Node.js and NPM, the mystical conduits to the world of JavaScript
  • Laravel, the spellbook that guides our path

Step 1: Conjuring a New Laravel Project🔮

Begin our adventure by conjuring a new Laravel project into existence. Utter the incantation:

composer create-project laravel/laravel laravel-websockets
cd laravel-websockets

Step 2: Unveiling the Power of Laravel WebSockets💫

Unveil the mystical power of Laravel WebSockets by installing the package:

composer require beyondcode/laravel-websockets -W

Next, unravel the hidden secrets by publishing the configuration and migrations:

php artisan vendor:publish --provider="BeyondCode\LaravelWebSockets\WebSocketsServiceProvider" --tag="migrations"
php artisan vendor:publish --provider="BeyondCode\LaravelWebSockets\WebSocketsServiceProvider" --tag="config"

Step 3: Channeling Energy with Environment Configuration🌟

Harness the cosmic energies of your environment by updating the .env file with the sacred incantations:

DB_CONNECTION=mysql
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE=your_database_name
DB_USERNAME=your_database_username
DB_PASSWORD=your_database_password

BROADCAST_DRIVER=pusher
PUSHER_APP_ID=websocketsappid
PUSHER_APP_KEY=sdasWWD
PUSHER_APP_SECRET=etsd$$TDSDA
PUSHER_HOST=127.0.0.1
PUSHER_PORT=6001
PUSHER_SCHEME=http
PUSHER_APP_CLUSTER=mt1

Step 4: Crafting Spells with Database Migrations📜

Craft potent spells to manifest your desires by migrating the database with the ancient command:

php artisan migrate
php artisan serve --host=0.0.0.0
php artisan websockets:serve

Then visit to http://0.0.0.0:8000/laravel-websockets

Then press connect

Step 5: Enchanting Events✨

Infuse your application with magic by updating the NewMessageEvent.php file to include the following code:

// app/Events/NewMessageEvent.php
namespace App\Events;
use Illuminate\Foundation\Events\Dispatchable;
use Illuminate\Queue\SerializesModels;
class NewMessageEvent
{
use Dispatchable, SerializesModels;
public $message;
public function __construct($message)
{
$this->message = $message;
}
}

Step 6: Unleash the Power of Laravel WebSockets🔥

With bated breath and trembling hands, unleash the raw power of Laravel WebSockets upon the world:

php artisan websockets:serve

Step 7: Witness the Magic Unfold🌈

Open a portal to your application’s realm by running the Laravel development server:

php artisan serve

Step 8: Embrace Real-Time Wonders🌌

Embrace the wonders of real-time communication as you journey to http://127.0.0.1:8000 in your browser. Behold, as the veil between reality and the digital realm fades, and the magic of Laravel WebSockets envelops you in its ethereal embrace!

Step 9: Illuminate Your Path with Vite.js✨

Illuminate your path to enlightenment by adding the sacred directive @vite('resources/js/app.js') to your app.blade.php file. This will empower your Laravel application with the enchanting powers of Vite.js for lightning-fast JavaScript bundling.

Here’s how you can integrate it into your app.blade.php file:

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Your Laravel WebSockets App</title>
<!-- Include the @vite directive to load your JavaScript assets -->
@vite('resources/js/app.js')
</head>
<body>
<!-- Your HTML content here -->

<!-- Example: -->
<div id="app">
<!-- Your Vue.js or React components can be rendered here -->
</div>
</body>
</html>

Step 10: Enhance Your Real-Time Spells with Laravel Echo and Pusher🔊

Enhance your real-time spells by incorporating Laravel Echo and Pusher into your magical arsenal. First, install the necessary dependencies:

npm install laravel-echo pusher-js

Next, infuse your resources/js/app.js file with the power of Laravel Echo and Pusher:

import './bootstrap';
import Echo from 'laravel-echo';
import Pusher from 'pusher-js';
window.Echo = new Echo({
broadcaster: 'pusher',
key: import.meta.env.VITE_PUSHER_APP_KEY,
cluster: import.meta.env.VITE_PUSHER_APP_CLUSTER ?? 'mt1',
wsHost: import.meta.env.VITE_PUSHER_HOST ? import.meta.env.VITE_PUSHER_HOST : `ws-${import.meta.env.VITE_PUSHER_APP_CLUSTER}.pusher.com`,
wsPort: import.meta.env.VITE_PUSHER_PORT ?? 80,
wssPort: import.meta.env.VITE_PUSHER_PORT ?? 443,
forceTLS: (import.meta.env.VITE_PUSHER_SCHEME ?? 'https') === 'https',
enabledTransports: ['ws', 'wss'],
});

Step 11: Test Your Real-Time Magic🔮

Now, test your real-time magic by adding the following code snippet to your web.php routes file:

// routes/web.php
use App\Events\NewMessageEvent;
Route::get('/test', function () {
event(new NewMessageEvent([
'message' => 'This is a test.',
'status' => true
]));
return view('test');
});

Conclusion: Embrace the Real-Time Magic✨

In this enchanting journey, we’ve unlocked the secrets of Laravel WebSockets, opening the gateway to a world of real-time wonders. So go forth, brave adventurer, and let your imagination soar as you craft extraordinary applications imbued with the essence of real-time enchantment! May your adventures be filled with wonder, and your code be ever magical! 🚀✨

--

--

Shaon Majumder
Shaon Majumder

Written by Shaon Majumder

Software Engineer | Author | Data Scientist

Responses (1)