Tuesday, July 16, 2019

push notifation : Pusher library

push notification : Real-time notifications in Laravel using Pusher


Real-time notifications are crucial to any application (web or mobile) and Pusher is one of the most popular services which helps you deliver real-time notifications to your applications. I have used Pusher on several projects and it was a delight to implement. It is a simple and straightforward process. So let us see how we can implement real-time notifications in this laravel pusher tutorial.

Prerequisites:

  • Sign up for a new account on Pusher.com and obtain your app_idkeysecret and also note down your cluster. These can be found in the App Keys section of your Pusher dashboard.

Setup your Laravel project:

  • See the official Laravel documentation for installation instructions on Laravel.
  • Require the pusher-php-server package in your laravel project using composer.
  • We will dump the composer autoload so our newly required package will be loaded by composer.
  • Create a PusherController which will hold our notification logic. We will also add a notify route to our file web.php, using which we will send notification using Pusher.

  • Add the below code to sendNotification() method of PusherController.
    • Here we first include Pusher (use Pusher\Pusher) in our PusherControllerand set our cluster and encryption keys in an options array. We then create a new Pusher object by providing our credentials and also passing in our $options array.
    • We can then publish to a channel and also specify a channel name. I have used nofify as the channel name and notify-event as the event name and these can be changed to any name you want. But remember to use the same channel name and event name in your front-end client.
  • Define a view route in your web.php file. The home.blade.php will hold our js code and will display an alert whenever a new notification is published to our channel.
  • Add the code below to home.blade.php.
  • That’s it! open up a new tab and visit www.your_domain.dev/notify while having the www.your_domain.dev/home open in another tab and you should see the alert!.
Real-time notifications in Laravel using Pusher_output
Of course, this was just a basic demo and you may use this in a more practical setting such as a notification widget or something like that but the core concept will remain the same. The source code for this tutorial is available on GitHub.
If you liked this laravel pusher tutorial then you might also like to read other ways of sending notifications in Laravel and be sure to leave any comments or ask any questions you might have in the comment section below!.