Evergreenbrain

Laravel and WebSockets

Real-Time Applications with Laravel and WebSockets

The demand for real-time communication and interaction in web applications has grown significantly over the past few years. Users expect instant updates and notifications without having to refresh their browsers. To meet these expectations, developers have turned to WebSockets, a powerful technology that enables real-time, full-duplex communication between a client and a server. In this tutorial, we will explore how to leverage Laravel and WebSockets to create real-time applications with seamless communication. Specifically, we will be using Laravel Echo, a JavaScript library that simplifies the process of subscribing to channels and listening for events.

Prerequisites

Before diving into this tutorial, make sure you have the following prerequisites installed:

  1. PHP installed on your local machine
  2. Composer for managing PHP dependencies
  3. Laravel installed globally
  4. A basic understanding of Laravel’s MVC structure and concepts

Setting Up Laravel Application
Firstly, let’s set up a new Laravel application. Open your terminal and run the following command:

Next, we need to install the beyondcode/laravel-websockets package. Run the following command in your terminal:


composer create-project --prefer-dist laravel/laravel laravel-websockets-app
cd laravel-websockets-app

Next, we need to install the beyondcode/laravel-websockets package. Run the following command in your terminal:


composer require beyondcode/laravel-websockets

After installing the package, you need to publish the package’s configuration file. Run the following command:


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

This command will create a websockets.php configuration file in your Laravel application’s config directory.

Now, let’s migrate the necessary database tables for WebSockets:


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

 


php artisan migrate

Configuring Laravel Echo Server
To handle broadcasting events, we need to set up a Laravel Echo Server. Install the server globally by running the following command:


npm install -g laravel-echo-server

After installing the server, navigate to your Laravel application directory and initialize the Echo Server configuration:


laravel-echo-server init

Follow the prompts and configure the server based on your application’s needs.

Implementing WebSockets in Laravel

Now that we have set up our Laravel application and configured the Echo server, let’s proceed with implementing WebSockets.

Event Broadcasting

Start by creating an event that you want to broadcast. Run the following command to create an event in Laravel:


php artisan make:event NewMessageEvent

Open the generated NewMessageEvent.php file in the app/Events directory and define your event. For example:


namespace App\Events;

use Illuminate\Broadcasting\Channel;
use Illuminate\Contracts\Broadcasting\ShouldBroadcast;
use Illuminate\Queue\SerializesModels;

class NewMessageEvent implements ShouldBroadcast
{
    use SerializesModels;

    public $message;

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

    public function broadcastOn()
    {
        return new Channel('chat');
    }
}

 

Broadcasting to WebSockets

In your application logic, broadcast the event to the WebSockets server. For instance, in a controller method:


use App\Events\NewMessageEvent;

public function sendMessage(Request $request)
{
    // Your logic to send the message

    event(new NewMessageEvent($message));
}

Listening for Events with Laravel Echo

To listen for events on the client-side, use Laravel Echo. First, install the Echo library via npm:


npm install --save laravel-echo pusher-js

In your JavaScript file, configure Laravel Echo to listen for events:


import Echo from "laravel-echo";
window.Echo = new Echo({
    broadcaster: 'pusher',
    key: process.env.MIX_PUSHER_APP_KEY,
    cluster: process.env.MIX_PUSHER_APP_CLUSTER,
    forceTLS: true,
    encrypted: true,
});

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

Running the Application

To run the application, start the Laravel development server and the Echo server in separate terminal windows:


php artisan serve
laravel-echo-server start

Open your application in the browser and test the real-time communication feature. You should be able to see the messages in the console log as they are broadcasted.

Conclusion
In this tutorial, we learned how to implement real-time features in a Laravel application using WebSockets and tools like Laravel Echo. We explored the setup process, event broadcasting, and event listening. By following these steps, you can integrate real-time communication seamlessly into your Laravel applications, providing users with a more engaging and interactive experience.

Real-time applications are becoming increasingly essential in modern web development, and with the power of Laravel and WebSockets, developers can create highly responsive and interactive applications that meet the demands of today’s users.

I hope this tutorial has helped you understand the basics of implementing real-time features with Laravel and WebSockets. With further exploration and experimentation, you can extend this functionality and create even more dynamic and sophisticated real-time applications.