Home Arrow Icon Knowledge base Arrow Icon Global Arrow Icon How do I register multiple custom guards for the /broadcasting/auth route
    Laravel 11 custom guards broadcasting authentication Laravel Echo web guard api guard admin guard customer guard


How do I register multiple custom guards for the /broadcasting/auth route


To register multiple custom guards for the `/broadcasting/auth` route in Laravel 11, you can follow these steps:

1. Define your custom guards in the `config/auth.php` file:

php
'guards' => [
    'web' => [
        'driver' => 'session',
        'provider' => 'users',
    ],
    'api' => [
        'driver' => 'token',
        'provider' => 'users',
    ],
    'admin' => [
        'driver' => 'session',
        'provider' => 'admins',
    ],
    'customer' => [
        'driver' => 'session',
        'provider' => 'customers',
    ],
],

In this example, we have defined two custom guards: `admin` and `customer`.

2. Specify the custom guards when defining the broadcast channels in the `routes/channels.php` file:

php
Broadcast::channel('admin-channel.{userId}', function ($user, $userId) {
    return (int) $user->id === (int) $userId;
}, ['guards' => ['admin']]);

Broadcast::channel('customer-channel.{userId}', function ($user, $userId) {
    return (int) $user->id === (int) $userId;
}, ['guards' => ['customer']]);

Here, we're using the `admin` guard for the `admin-channel.{userId}` channel and the `customer` guard for the `customer-channel.{userId}` channel.

3. When a client attempts to subscribe to a private channel, Laravel Echo will send an HTTP request to the `/broadcasting/auth` route. Laravel will use the specified custom guards to authenticate the user.

4. If the user is authenticated using the custom guards, the authorization callback will be executed to determine if the user is authorized to access the channel.

By specifying the `guards` option when defining the broadcast channels, you can instruct Laravel to use your custom authentication guards for those specific channels.

Make sure that your custom guard implementations are compatible with the authentication logic used in your application. The custom guards should be able to authenticate the users and provide the necessary user information for the authorization callbacks to work correctly.

Citations:
[1] https://github.com/laravel/framework/issues/16151
[2] https://laracasts.com/discuss/channels/laravel/broadcasting-auth-with-custom-auth-guard
[3] https://stackoverflow.com/questions/59531249/custom-multi-auth-guard-logging-routing
[4] https://techvblogs.com/blog/multiple-authentication-guards-laravel-9
[5] https://laracasts.com/discuss/channels/laravel/how-to-use-custom-guard-with-laravel-broadcasting