Real-time notifications in Laravel using Pusher

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_id`, `key`, `secret` 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`.
    $ composer require pusher/pusher-php-server
  • We will dump the composer autoload so our newly required package will be loaded by composer.
    $ composer dumpautoload
  • 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.
    $ php artisan make:controller PusherController
    //web.php
    
    Route::get('/notify', '[email protected]');
  • Add the below code to `sendNotification()` method of `PusherController`.
    <?php
    
    namespace App\Http\Controllers;
    
    use Illuminate\Http\Request;
    use Pusher\Pusher;
    
    class PusherController extends Controller
    {
    
        public function sendNotification()
        {
            //Remember to change this with your cluster name.
            $options = array(
                'cluster' => 'ap2', 
                'encrypted' => true
            );
    
           //Remember to set your credentials below.
            $pusher = new Pusher(
                'key',
                'secret',
                'app_id',
                $options
            );
    	    
            $message= "Hello User";
    		
            //Send a message to notify channel with an event name of notify-event
            $pusher->trigger('notify', 'notify-event', $message);  
        }
    }
    • 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.
    Route::view('/home', 'home');
  • Add the code below to home.blade.php.
    <!DOCTYPE html>
    <html lang="en">
      <head>
        <meta charset="utf-8">
        <meta http-equiv="X-UA-Compatible" content="IE=edge">
        <meta name="viewport" content="width=device-width, initial-scale=1">
        <title>Real-time notifications in Laravel using Pusher</title>
    
      </head>
      <body>
        <h1>Real-time notifications in Laravel using Pusher</h1>
    
        <!-- Incldue Pusher Js Client via CDN -->
        <script src="https://js.pusher.com/4.2/pusher.min.js"></script>
        <!-- Alert whenever a new notification is pusher to our Pusher Channel -->
    
        <script>
        //Remember to replace key and cluster with your credentials.
        var pusher = new Pusher('key', {
          cluster: 'ap2',
          encrypted: true
        });
    
        //Also remember to change channel and event name if your's are different.
        var channel = pusher.subscribe('notify');
        channel.bind('notify-event', function(message) {
            alert(message);
        });
    
        </script>
      </body>
    </html>
  • 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!.

P.S:

You can also consider making a small donation to support me. Your donation will directly contribute to the running cost of this website and hopefully my college too 🙂

Paypal: https://www.paypal.me/sapneshnaik  |  UPI: [email protected]

16
Leave a Reply

avatar
8 Comment threads
8 Thread replies
6 Followers
 
Most reacted comment
Hottest comment thread
8 Comment authors
Ronak BhabhorSaluSapnesh NaikJehnsenAnonymouse703 Recent comment authors
  Subscribe  
newest oldest most voted
Notify of
robert
Guest
robert

You should change your first line of code to ‘composer require pusher/pusher-php-server “~3.0” ‘ without version composer will not install package because of RC permission.

Lasa
Guest
Lasa

Hey i want to submit dynamic data i will do

Shahrukh
Guest
Shahrukh

Nice short and to the point tutorial

Anonymouse703
Guest
Anonymouse703

Hi dude, I been stuck for a month now about Laravel Notification and what’s in google is all about slack, pusher email, database… But how about for incoming github webhook?

My problem is how to make a Laravel Notifcation for github push event.

Case: If the owner of the repo has update the webhook will send into my Laravel app and notify the admin or a specific user.. any ideas?

I don’t know how to set up Laravel notifications and where to put the guzzle request..

Thank you… Hope you will help me.

Jehnsen
Guest
Jehnsen

Hi sir! your demo is very useful, but can I add multiple parameters in sendNotification method in controller like for example :
public function sendNotification($id, $message)
{
//Remember to change this with your cluster name.
$options = array(
‘cluster’ => ‘ap1’,
‘encrypted’ => true
);
//Remember to set your credentials below.
$pusher = new Pusher(
‘193a1f2074df4f736409′,
’32cf09f84b91b7539e96’,
‘627515’,
$options
);
// $message= “Hello User”;
//Send a message to notify channel with an event name of notify-event
$pusher->trigger(‘notify’, ‘notify-event’, [$id, $message]);
} I also want to pass the id parameter to the notification. any help please. thanks in advance!

Jehnsen
Guest
Jehnsen

Hi sir! your demo is very useful, but can I add multiple parameters in sendNotification method in controller like for example :
public function sendNotification($id, $message)
{
$options = array(
‘cluster’ => ‘ap1’,
‘encrypted’ => true
);
$pusher = new Pusher(
‘xxxxxxxxxxxxxxxxxxxxxx’,
‘xxxxxxxxxxxxxxxxxxxxxx’,
‘xxxxxx’,
$options
);
$pusher->trigger(‘notify’, ‘notify-event’, [$id, $message]);
} I also want to pass the id parameter to the notification. any help please. thanks in advance!

salu
Guest
salu

sir, can i use other javascript alert plugins instead of default alert ..?Pls reply me

Ronak Bhabhor
Guest
Ronak Bhabhor

this is very useful for me, thank you for this article