Laravel live notification using Pusher

Laravel live notification using Pusher

Laravel has the default broadcast option for notifying or updating user interfaces, for example, if your user wants to create large volumes of data in Excel format, which may take longer. So instead of waiting, you can use Pusher to notify them when the report creation is complete.

We are not going to look at the whole process of push into specific users. Instead, we will outline how to use the pusher to notify.

So without further talk, let’s look at how to create a live notification using Pusher in Laravel

Step 1 Install Pusher package

composer require pusher/pusher-php-server

after installing that update Pusher credentials in config/broadcasting.php (you can get your Pusher credentials from their official site from here )

PUSHER_APP_ID=your-pusher-app-id
PUSHER_APP_KEY=your-pusher-key
PUSHER_APP_SECRET=your-pusher-secret
PUSHER_APP_CLUSTER=mt1

Update .env file with the below code.

BROADCAST_DRIVER=pusher

Step 2 Update Broadcast Service Provider

in config/app.php, add or uncomment the following line in the providers section.

App\Providers\BroadcastServiceProvider::class,

Step 3 Install npm and other packages

npm install

We can subscribe and listen events by using the following package,

npm install --save laravel-echo pusher-js

Once installed, we need to tell Laravel Echo to use Pusher. In resources/assets/js/bootstrap.js file update the below codes at last,

import Echo from "laravel-echo"
window.Pusher = require('pusher-js');

window.Echo = new Echo({
    broadcaster: 'pusher',
    key: 'your-key',
    cluster: 'mt1',
    encrypted: true
});

Step 4 Create an event – MyNotificationEvent

Change the broadcast channel type as shown below,

public function broadcastOn()
{
   return new Channel('my_notification_event');
}

You can also return data with your events like below,

public function broadcastWith()
{
    return [
        'message' => 'success',
    ];
}

Step 5 – Call MyNotificationEvent in the controller

public function your_function(Request $request){
   broadcast(new MyNotificationEvent($var));
}

Step 6 Listen to events and notify using Echo

window.Echo.channel('my_notification_event')
.listen('MyNotificationEvent', (e) =>{
   alert('Notified successfully!');
})

Conclusion

I hope this gave you a basic knowledge of Pusher and how to use it in Laravel. If you have any doubts, feel free to ask in the comments section below

Cheers!