Building Real-Time Applications with WebSockets and Laravel 8: A Complete Guide

WebSockets have revolutionized the way we build real-time applications. Instead of relying on traditional HTTP requests and responses, WebSockets allow us to establish long-lived, bidirectional connections between the client and server, enabling real-time data exchange without the need for constant polling.

In this article, we’ll explore how to integrate WebSockets into your Laravel 8 application, and we’ll provide a complete example to demonstrate how WebSockets can be used to build a real-time chat application.

What are WebSockets?

WebSockets are a protocol for real-time, bidirectional communication between the client and server. Unlike traditional HTTP requests, which are unidirectional and stateless, WebSockets allow the client and server to maintain a persistent connection, enabling real-time data exchange without the need for constant polling.

The WebSocket protocol is supported by all modern browsers, and it’s widely used in real-time applications such as chat apps, multiplayer games, and financial trading platforms.

Integrating WebSockets into Laravel 8

Laravel 8 makes it easy to integrate WebSockets into your application using the Laravel WebSockets package. The Laravel WebSockets package provides a WebSocket server implementation, as well as a JavaScript client library for connecting to the server.

To get started, you’ll need to install the Laravel WebSockets package using Composer:

composer require beyondcode/laravel-websockets

Configuring Laravel WebSockets

Once you’ve installed the Laravel WebSockets package, you’ll need to configure it for your application. The configuration file can be found at config/websockets.php.

The most important configuration option is the apps option, which defines the WebSocket applications that your server will host. An application is a logical group of channels that clients can subscribe to. Each application has a unique key and secret, which are used to authenticate clients.

Here’s an example configuration file:

'apps' => [['id' => 'your-app-id','name' => 'Your App Name','key' => 'your-app-key','secret' => 'your-app-secret','capacity' => null,'enable_client_messages' => true,'enable_statistics' => true,],],

In this example, we define a single application with the ID your-app-id, the name Your App Name, and the key and secret values that clients will use to authenticate.

You can define as many applications as you need, depending on the requirements of your application.

Running the WebSocket Server

Once you’ve configured Laravel WebSockets, you can start the WebSocket server by running the following Artisan command:

php artisan websockets:serve

This will start the WebSocket server on port 6001 by default. You can change the port by passing the --port option:

php artisan websockets:serve --port=8080

Make sure that your server is configured to allow incoming connections on the WebSocket port.

Connecting to the WebSocket Server

Once the WebSocket server is running, you can connect to it using the JavaScript client library provided by Laravel WebSockets. The client library is included by default in Laravel 8, so you don’t need to install any additional packages.

Here’s an example of how to connect to the WebSocket server:

import Echo from 'laravel-echo';

window.Echo = new Echo({broadcaster: 'pusher',key: 'your-app-key',wsHost: window.location.hostname,wsPort: 6001,disableStats: true,});

In this example, we import the Echo class from the Laravel Echo package, which provides a simple API for interacting with WebSockets. We then create a new instance of the Echo class, passing in the necessary configuration options:

  • The broadcaster option specifies the WebSocket transport to use. Laravel WebSockets supports several transports, including Pusher, Redis, and AWS.
  • The key option specifies the key value of the WebSocket application that we defined in the previous section.
  • The wsHost and wsPort options specify the WebSocket server hostname and port.
  • The disableStats option disables real-time statistics for performance reasons.

Building a Real-Time Chat Application with WebSockets and Laravel 8

Now that we’ve covered the basics of WebSockets and how to integrate them into Laravel 8, let’s build a real-time chat application to demonstrate how WebSockets can be used in practice.

Creating the Laravel Application

First, let’s create a new Laravel 8 application using the following Artisan command:

composer create-project --prefer-dist laravel/laravel laravel-websockets-example

Next, let’s install the Laravel WebSockets package using Composer:

composer require beyondcode/laravel-websockets

Finally, we’ll publish the Laravel WebSockets configuration file using the following Artisan command:

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

Creating the Chat Controller

Next, let’s create a new controller to handle chat messages. We’ll create a new controller called ChatController using the following Artisan command:

php artisan make:controller ChatController

Next, let’s add a method to the ChatController called sendMessage. This method will handle incoming chat messages from clients:

public function sendMessage(Request $request){$message = $request->input('message');$user = Auth::user();

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

return response()->json(['status' => 'Message Sent!']);}

In this example, we retrieve the chat message and the authenticated user from the request. We then broadcast the message to all connected clients using the broadcast function, passing in a new instance of the MessageSent event. Finally, we return a JSON response to indicate that the message was sent successfully.

Creating the MessageSent Event

Next, let’s create a new event called MessageSent using the following Artisan command:

php artisan make:event MessageSent

Next, let’s define the MessageSent event in the app/Events/MessageSent.php file:

class MessageSent implements ShouldBroadcast{use Dispatchable, InteractsWithSockets, SerializesModels;

public $user;public $message;

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

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

In this example, we define a new event class called MessageSent, which implements the ShouldBroadcast interface. The ShouldBroadcast interface indicates that this event should be broadcast to all connected clients.

The $user and $message properties of the event class contain the user and message data that we want to broadcast to clients.

The broadcastOn method specifies the channel that the event should be broadcast on. In this example, we’re using a private channel called chat, which ensures that only authenticated users can receive chat messages.

Creating the Chat View

Finally, let’s create a new view to display the chat messages. We’ll create a new view called chat.blade.php in the resources/views directory:

<html><head><title>Laravel WebSockets Chat Example</title></head><body><div id="chat"><ul id="messages"></ul></div>

<form id="chat-form"><input id="chat-message" type="text"><button type="submit">Send</button></form>

<script src="{{ asset('js/app.js') }}"></script>

<script>const chatForm = document.getElementById('chat-form');const chatMessageInput = document.getElementById('chat-message');const messagesList = document.getElementById('messages');

chatForm.addEventListener('submit', event => {event.preventDefault();

const message = chatMessageInput.value.trim();

if (message === '') {return;}

axios.post('/chat', {message: message});

chatMessageInput.value = '';});

Echo.private('chat').listen('MessageSent', (event) => {const message = document.createElement('li');const user = event.user.name;

message.innerHTML = user + ': ' + event.message;messagesList.appendChild(message);});</script></body></html>

In this example, we define a simple HTML structure for displaying the chat messages, as well as a form for submitting new messages. We also include the JavaScript client library provided by Laravel WebSockets.

The JavaScript code listens for the submit event on the chat form, and sends a new chat message to the server using an AJAX request. It then clears the chat message input field.

The code also listens for the MessageSent event on the chat private channel, and appends new chat messages to the messagesList element.

Testing the Chat Application

Now that we’ve created the chat controller, event, view, and JavaScript code, let’s test the chat application.

First, let’s start the Laravel WebSockets server using the following Artisan command:

php artisan websockets:serve

Next, let’s start the Laravel development server using the following Artisan command:

php artisan serve

Finally, let’s visit the chat page in our browser at http://localhost:8000/chat. We should see a simple chat interface with a form for sending messages.

Try sending a few chat messages using different browsers or devices, and observe how the messages are broadcast in real-time to all connected clients.

Conclusion

In this article, we’ve explored how WebSockets can be integrated into Laravel 8 to build real-time applications. We’ve provided a complete example of how WebSockets can be used to build a real-time chat application, and we’ve covered the basics of configuring the Laravel WebSockets package, connecting to the WebSocket server, and broadcasting events to connected clients.

We hope that this article has provided you with a solid foundation for building your own real-time applications with WebSockets and Laravel 8.

FAQ

What is Laravel 8?

Laravel is a popular PHP web application framework that makes it easy to build modern, scalable applications. Laravel 8 is the latest version of Laravel, released in September 2020.

What are WebSockets used for?

WebSockets are used for real-time, bidirectional communication between the client and server. They’re commonly used in real-time applications such as chat apps, multiplayer games, and financial trading platforms.

What is the Laravel WebSockets package?

The Laravel WebSockets package is a third-party package that provides a WebSocket server implementation for Laravel 8. It also provides a JavaScript client library for connecting to the server.

How do I install the Laravel WebSockets package?

You can install the Laravel WebSockets package using Composer, the PHP package manager. Simply run the following command in your Laravel 8 application directory:

composer require beyondcode/laravel-websockets

How do I start the Laravel WebSockets server?

You can start the Laravel WebSockets server using the following Artisan command:

php artisan websockets:serve

This will start the WebSocket server on port 6001 by default. You can change the port by passing the --port option:

php artisan websockets:serve --port=8080

How do I connect to the Laravel WebSockets server?

You can connect to the Laravel WebSockets server using the JavaScript client library provided by Laravel WebSockets. The client library is included by default in Laravel 8, so you don’t need to install any additional packages.

Here’s an example of how to connect to the WebSocket server:

import Echo from 'laravel-echo';

window.Echo = new Echo({broadcaster: 'pusher',key: 'your-app-key',wsHost: window.location.hostname,wsPort: 6001,disableStats: true,});

How do I broadcast an event to connected clients?

You can broadcast an event to connected clients using the broadcast function provided by Laravel WebSockets. Here’s an example:

broadcast(new MyEvent($data))->toOthers();

This code broadcasts a new instance of the MyEvent event to all connected clients, except for the current client that triggered the event.