1 year ago

Passing Data to Broadcasted Event Authorization Callback

Posted 1 year ago by nickdavies07

I've just started looking at event broadcasting using Laravel Echo, Laravel Websockets and Vue. I'd like to create a new alert popup which shows when a new asset is created. This alert should only show if the user has access to the school that the new asset is being created for. Something like this: alert-example

My table relationships: I have users, schools and assets tables. Users can belong to many schools and vice versa. An asset can belong to a school, and schools can have many assets.

I have a new event called AssetCreated which is fired when a new asset is created event(new AssetCreated(auth()->user(), $asset)); This event accepts the authenticated user and the asset that has been created. I then have an AssetCreated class:-

    public function broadcastOn()
        return new PrivateChannel('assets');

I've read in the documentation that you can pass the data to the channel like this:-

    public function broadcastOn()
        return new PrivateChannel('assets.' . $this->assets->school_id);
Broadcast::channel('assets.{schoolId}', function ($user, $schoolId) {
    return $user->schools->contains($schoolId)

But with this approach I then have to pass the data to Laravel Echo in the Vue component as well...

    .listen('AssetCreated', ({user}) => {
        this.alert = true;

I'd like to keep the channel name as assets, but I need to verify that the user has access to that asset's school. What would be the best way of approaching this?

Please sign in or create an account to participate in this conversation.