When you try to set up private channels in my case I use JWTTokens in laravel. For doing that in /config/auth.php you need to establish the guard that we will use to get the authenticated user
'guards' => [ 'web' => [ 'driver' => 'session', 'provider' => 'users', ], 'api' => [ 'driver' => 'jwt', 'provider' => 'users', ], ],
In the last piece of code we put for api guard we get the authenticated user from JWT.
In BroadcastServiceProvider we define the routes
class BroadcastServiceProvider extends ServiceProvider { /** * Bootstrap any application services. * * @return void */ public function boot() { Broadcast::routes(); require base_path('routes/channels.php'); }}
In routes/channels.php we establish the route for the private channel and WE MUST ADD THE GUARD OPTION in the declaration of the route
Broadcast::channel('fileszipped.{id}', function ($user, $id) { return $user->id == $id;}, ['guards' => ['api']]);
Then in the event, that we use to broadcast the message we declare that we broadcast the message over the channel declared. You should pass in the constructor of this event, the authenticated user:
class FileZipped implements ShouldBroadcast { use Dispatchable, InteractsWithSockets, SerializesModels; /** * The file instance. * * @var FilesUser */ public $fileUser; /** * Create a new event instance. * * @return void */ public function __construct($fileUser) { $this->fileUser = $fileUser; } /** * Get the channels the event should broadcast on. * * @return \Illuminate\Broadcasting\Channel|array */ public function broadcastOn() { return new PrivateChannel('fileszipped.'.$this->fileUser->user->id); }}
Finally, in the front, I used React v17 I declare this
const options = { broadcaster: "pusher", key: "123456_key", cluster: "mt1", forceTLS: false, encrypted: false, wsHost: '127.0.0.1', wsPort: 6001, //authEndpoint is your apiUrl + /broadcasting/auth authEndpoint: "http://localhost:8000/broadcasting/auth", // As I'm using JWT tokens, I need to manually set up the headers. auth: { headers: { Authorization: "Bearer " + auth.accessToken, Accept: "application/json" } } }; const echo = new Echo(options); useEffect(() => { echo.private(`fileszipped.`+ auth.id) .listen('FileZipped', (e) => { console.log(e.fileUser.name); setMessage(e.fileUser.name + ' is ready for download!!'); getAllFilesUser() }); }, [])
By doing this you will receive your notifications in the front using private channels. Enjoy it!!