Skip to main content

Allowing guests to join Laravel Echo presence channels using Laravel 11

After the release of Laravel 11, I started to play around with Reverb, their first-party WebSocket server. I wanted to allow guests to join presence channels, however, this was not possible because the documentation states that private and presence channels require authorization. That's when I stumbled across this helpful StackOverflow answer by jbwilhite.

Solution

In version 11, Laravel simplified the application skeleton, making parts of the answer outdated. You can find the updated solution below. Here's the modifications you need to make:

In routes/channels.php:

<?php

use Illuminate\Support\Facades\Broadcast;

Broadcast::routes([
    'middleware' => ['web', 'authenticate-guest'],
]);

Broadcast::channel('your-presence-channel', function ($user) {
    return ['id' => $user->id, 'name' => $user->id];
});

In bootstrap/app.php:

->withMiddleware(function (Middleware $middleware) {
    $middleware->alias([
        'authenticate-guest' => \App\Http\Middleware\AuthenticateGuest::class
    ]);
})

And finally in app/Http/Middleware/AuthenticateGuest.php:

public function handle(Request $request, Closure $next): Response
{
    if (Auth::hasUser()) {
        return $next($request);
    }

    Auth::login(User::factory()->make([
        'id' => (int)str_replace('.', '', microtime(true))
    ]));

    return $next($request);
}

I stayed close to the original answer, however, I tweaked the middleware, only signing in the user if he's not already signed in. Furthermore, I updated the user creation by using more modern User::factory() syntax. Finally, I changed the way the middleware alias is registered to be Laravel 11 compatible.

Using this approach, guests can join presence channels. An alternative solution, albeit more difficult, would be to create a custom Guard class and attach it to the presence channel as mentioned in the section Authorization Callback Authentication.

Published on March 13, 2024
Last modified on March 13, 2024

Did you like what you read? Feel free to share! Make sure to follow me on Twitter to stay in the loop.