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

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


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']);


I finally figured out how to do it.

I am not sure if it is the best way of achieving this, and I'd highly appreciate any improvements.

How I achieved is created a new middleware for 'web' and left the other one as it it. Here are the steps.

1) In 'BroadcastServiceProvider', left only auth:api guard for Broadcast::routes(['middleware' => 'auth:api']);.

This way, Laravel's auth:api method for authenticating broadcasting works as expected.

2) Created a middleware called "Broadcast" and mapped it in Kernel.php like so:

'broadcast' => \App\Http\Middleware\Broadcast::class

and the Broadcast.php middleware looks like this:

public function handle($request, Closure $next){    $web = Auth::guard('web')->user();    if ($web) {        return response()->json(\Illuminate\Support\Facades\Broadcast::auth($request));    }    return response()->json('Unauthorized.', 500);}

3) Created a unique route other than Laravel's /broadcasting/auth in my routes>web.php

Route::post('/guard/broadcast/auth', function(\Illuminate\Support\Facades\Request $req){    return true;})->middleware('broadcast');

4) And then only on my blade, I use it like so:

<script>let pusher = new Pusher("{{ env('PUSHER_APP_KEY') }}", {    cluster: 'us2',    encrypted: true,    auth: {        headers: {            'X-CSRF-TOKEN': "{{ csrf_token() }}"        }    },    authEndpoint: '{{ env('APP_URL') }}' + '/guard/broadcast/auth',});let channel = pusher.subscribe('private-channel.{{ Auth::user()->id }}');channel.bind('my-event', addMessage);function addMessage(data) {    console.log(data);}</script>


I'm preferable just using middleware that extends to both auth:api and web middlewares.

like what I posted in here: https://github.com/tlaverdure/laravel-echo-server/issues/266#issuecomment-365599129. So, I just maintenance 1 middleware if I wanted to change it in the future