laravelmiddlewarelaravel-5.5laravel-passportlaravel-events

Laravel Broadcast - Combining multiple middleware (web, auth:api)


I am using Laravel Event Broadcast and Pusher to utilize websockets both on my API and Web. If I try them individually, both work fine. What I mean is:

Broadcast::routes(['middleware' => 'web']); // this works for my Laravel website

Broadcast::routes(['middleware' => 'auth:api']); // this works for my api

However, if I want to use both at the same time like this:

Broadcast::routes(['middleware' => ['auth:api', 'web']]); // doesn't work

... it crashes for both, which I suspect that it is assuming I am trying to enable for both auth:api && web middlewares.

Is there a way to use an OR kind of statement for this (auth::api || 'web')? What if I want to use both at the same time and if it passes one middleware, it bypasses the middleware.

Please note that I am using Laravel Passport for my api.


Or is there a way to combine and creating a mixed middleware for both (which will essentially check for either api or web)? So I can use something like this maybe:

Broadcast::routes(['middleware' => 'broadcast']); // or auth:broadcast

Update:

As far as I understand, if I create a new Middleware called broadcast, I can do:

class BroadcastMiddleware() {

  public function handle() {
    $web = Auth::guard('web')->user();
    if ($web) {
        return response()->json($web);
    }

    $api = Auth::guard('api')->user();
    if ($api) {
        return response()->json($api);
    }
    return response()->json('Unauthorized.', 500);
  }
}

But then how do I change /broadcasting/auth route? If I try this:

Route::post('/realtime/auth', function(){
    return true;
})->middleware('broadcast');

This returns the user object info, however instead, it should return something like: auth:"374f7ff42b7da877aa35:c29addedec281b418331a61dc3cfc74da8b108222565fa4924a8..."


Solution

  • Why not just use something like this in the BroadcastServiceProvider? This creates two separate endpoints with separate middleware assigned.

        Broadcast::routes(['middleware' => 'web']);
    
        Broadcast::routes(['prefix' => 'api', 'middleware' => 'api']);