Laravel Websockets without Pusher: A Complete Guide

If you are a Laravel developer, you must have heard about Websockets, which are essential for real-time applications. Websockets allow you to establish a persistent connection between the client and the server, enabling real-time communication. While there are various third-party services like Pusher that provide Websockets support, Laravel also has its own Websockets package. In this article, we will explore how to use Laravel Websockets without Pusher.

What are Websockets?

Websockets are a protocol that allows two-way communication between a client and a server over a persistent connection. Unlike traditional HTTP requests, which are stateless and require a new connection for each request, Websockets allow you to establish a connection once and keep it open for as long as required. This makes them ideal for real-time applications where the server needs to push updates to the client immediately.

Why use Laravel Websockets?

Laravel Websockets is a package that provides a simple and easy-to-use interface for working with Websockets in Laravel. It is built on top of the popular Ratchet library and provides features like broadcasting, presence channels, and authentication out of the box. Using Laravel Websockets allows you to add real-time functionality to your Laravel application quickly and easily.

Installing Laravel Websockets

The first step to using Laravel Websockets is to install it in your Laravel application. You can do this using Composer by running the following command:

composer require beyondcode/laravel-websockets

This will install the package and all its dependencies. Next, you need to publish the configuration file by running the following command:

php artisan vendor:publish –provider=”BeyondCode\LaravelWebSockets\WebSocketsServiceProvider” –tag=”config”

This will create a new file called websockets.php in your config directory. This file contains all the configuration options for Laravel Websockets.

Configuring Laravel Websockets

Once you have installed Laravel Websockets, you need to configure it for your application. The websockets.php file contains several configuration options that you can modify to suit your needs.

Pusher API Key

If you are not using Pusher, you can remove the PUSHER_APP_ID, PUSHER_APP_KEY, and PUSHER_APP_SECRET options from the configuration file.

Redis

Laravel Websockets uses Redis to store information about the WebSocket connections. You can configure the Redis connection by modifying the redis section of the websockets.php file.

SSL

If you are using SSL, you need to specify the SSL certificate and key paths in the ssl section of the configuration file.

Other Options

The websockets.php file contains several other options that you can modify to suit your needs. These include the port number, the maximum number of connections, and the maximum payload size.

Starting Laravel Websockets

Once you have configured Laravel Websockets, you can start the server by running the following command:

php artisan websockets:serve

This will start the server and listen for WebSocket connections on the specified port.

Using Laravel Websockets

Now that you have started the Laravel Websockets server, you can start using it in your Laravel application. Laravel Websockets provides several features that make it easy to work with Websockets in Laravel.

Broadcasting

Laravel Websockets provides a simple interface for broadcasting events to all connected WebSocket clients. You can define an event using Laravel’s event system and broadcast it using the broadcast method.

Defining an Event

To define an event, you need to create a new class that extends Laravel’s Illuminate\Contracts\Broadcasting\ShouldBroadcast interface. This interface requires you to implement a single method, broadcastOn, which should return the channel or channels that the event should be broadcast on.

For example, let’s say we want to broadcast a new message event to all connected clients:

namespace App\Events;

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

class NewMessage implements ShouldBroadcast{public $message;

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

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

In this example, we define a new NewMessage event that takes a message as its constructor argument. The broadcastOn method returns a new Channel object with the name chat, indicating that the event should be broadcast on the chat channel.

Broadcasting an Event

Once you have defined an event, you can broadcast it using Laravel’s event system. To do this, you need to call the broadcast method with the event instance as its argument:

event(new NewMessage('Hello, world!'));

This will broadcast the NewMessage event to all connected clients on the chat channel.

Presence Channels

Laravel Websockets also provides support for presence channels, which allow you to track which users are connected to a channel. To use presence channels, you need to modify your event class to implement the Illuminate\Contracts\Broadcasting\ShouldBroadcastNow interface instead of ShouldBroadcast.

For example, let’s say we want to track which users are connected to the chat channel:

namespace App\Events;

use Illuminate\Broadcasting\Channel;use Illuminate\Contracts\Broadcasting\ShouldBroadcastNow;use Illuminate\Contracts\Support\Arrayable;

class UserJoined implements ShouldBroadcastNow, Arrayable{public $user;

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

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

public function broadcastWith(){return ['user' => $this->user,];}

public function toArray(){return ['user' => $this->user,];}}

In this example, we define a new UserJoined event that takes a user object as its constructor argument. The broadcastOn method returns a new Channel object with the name chat, indicating that the event should be broadcast on the chat channel.

The broadcastWith method returns an array of data that should be included in the broadcast payload. In this example, we include the user object in the payload.

The toArray method is used to convert the event instance to an array when broadcasting to presence channels.

Authentication

Laravel Websockets also provides support for authenticating WebSocket connections. To authenticate a connection, you need to define a class that implements the BeyondCode\LaravelWebSockets\Contracts\WebSocketAuthenticationContract interface and register it in the websockets.php configuration file.

For example, let’s say we want to authenticate WebSocket connections using a JWT token:

namespace App\Services;

use BeyondCode\LaravelWebSockets\Contracts\WebSocketAuthenticationContract;use Illuminate\Http\Request;

class JwtAuthenticator implements WebSocketAuthenticationContract{public function canBeAuthenticated(Request $request): bool{return $request->hasHeader('Authorization') && starts_with($request->header('Authorization'), 'Bearer ');}

public function authenticate(Request $request): bool{$token = substr($request->header('Authorization'), 7);

// Authenticate the token here

return true;}}

In this example, we define a new JwtAuthenticator class that implements the WebSocketAuthenticationContract interface. The canBeAuthenticated method checks if the request contains a JWT token in the Authorization header, and the authenticate method authenticates the token.

To register the authenticator, you need to add it to the authenticators option in the websockets.php configuration file:

'authenticators' => [\App\Services\JwtAuthenticator::class,],

Once you have registered the authenticator, Laravel Websockets will automatically use it to authenticate WebSocket connections.

FAQ

What is Pusher?

Pusher is a third-party service that provides Websockets support for real-time applications. It provides an easy-to-use API for working with Websockets and supports features like presence channels and authentication.

Why use Laravel Websockets?

Laravel Websockets is a package that provides a simple and easy-to-use interface for working with Websockets in Laravel. It is built on top of the popular Ratchet library and provides features like broadcasting, presence channels, and authentication out of the box. Using Laravel Websockets allows you to add real-time functionality to your Laravel application quickly and easily.

Can I use Laravel Websockets without Pusher?

Yes, you can use Laravel Websockets without Pusher. Laravel Websockets provides all the features you need to work with Websockets in Laravel, including broadcasting, presence channels, and authentication.

How do I install Laravel Websockets?

You can install Laravel Websockets using Composer by running the following command:

composer require beyondcode/laravel-websockets

This will install the package and all its dependencies. You also need to publish the configuration file by running the following command:

php artisan vendor:publish –provider=”BeyondCode\LaravelWebSockets\WebSocketsServiceProvider” –tag=”config”

This will create a new file called websockets.php in your config directory.

How do I start Laravel Websockets?

You can start Laravel Websockets by running the following command:

php artisan websockets:serve

This will start the server and listen for WebSocket connections on the specified port.

How do I broadcast an event using Laravel Websockets?

You can broadcast an event using Laravel’s event system and the broadcast method. First, you need to define an event class that implements the ShouldBroadcast or ShouldBroadcastNow interface and specifies the channel or channels that the event should be broadcast on. Then, you can broadcast the event using the broadcast method and passing the event instance as its argument.

How do I authenticate WebSocket connections using Laravel Websockets?

You can authenticate WebSocket connections using a custom authenticator class that implements the WebSocketAuthenticationContract interface. You can register the authenticator in the websockets.php configuration file and Laravel Websockets will automatically use it to authenticate WebSocket connections.