My Programming Tutorials

My Programming Tutorials

Web Notifications Using Laravel and Pusher

Last updated on by , 4 comments

Web notification is a particular message that generates from a website, whenever any update or important message is shared on the app. These messages pop up on your desktop or device even when the respective page is not opened on your current browser.

These push notifications are a great addition to the traditional email and marketing campaigns. As a user is notified with a push notification every time whenever any update is generated and the users just have to click on that to be notified about any update.

Pusher

Pusher is a hosted service that allows web and mobile applications to add real time data to its live functionality. It works as a real time correspondent between the servers and clients. It establishes persistent connections with the clients on HTTP using WebSocket, therefore, whenever your server receives new data, it gets instantly passed on to the respective clients for maintaining live data concurrency.

In order to integrate in all major languages and frameworks, Pusher offers several libraries to achieve the integration, including libraries of PHP, Ruby, Python, Java, .NET, Go and Node for the server, and JavaScript, Objective-C (iOS) and Java (Android) for the client.

Being known as a highly scalable real time solution for apps, Pusher first came to prominence in 2010 and since then it has continued to remain as the top choice for many. The list of its happy customers includes GitHub, MailChimp, CodeShip, The Financial Times, UserVoice, Travis CI and many others.

Pusher Real-time Use Cases

Pusher has a number of common use cases for real-time web technologies including:

  1. Activity Streams
  2. Data Visualisations/Dashboards
  3. Notifications & Signalling
  4. Collaborative Apps
  5. Chat
  6. Multiplayer Games

The simplest use case of Pusher is the real time notifications. Whenever something relevant occurs according to the website user’s journey, it automatically pops up a notification for the event. This is the same functionality we have seen on Twitter, Facebook and in many other social media platforms for years.

Notification can also be seen as a form of signaling, as it does not contains any organized representation in the UI of the application, but still triggers a reaction within an application.

As far as the current social web apps are concerned, it is very common to have interactive real time notifications. We have the examples of Facebook, Twitter and other social networking sites, which support integration of creative built-in notification systems within them. In this regard, Pusher is one of the most used and popular services which helps you incorporate real-time notifications to your apps and helps you make them more lively and interactive.

In this blog, I will demonstrate about how to implement real time notification system using Laravel and Pusher.

Prerequisites

For the purpose of this tutorial, I assume that you have a Laravel application installed on a web server. My setup is:

  • Laravel 5.5
  • Pusher

I have decided to host my Laravel application on PHP MySQL hosting. It has great devstack and is known for its highly secured platform. You can also try out Cloudways for free by signing up for an account

Setup your Pusher Account

After successfully completing Laravel installation, now let’s create a Pusher account to get API key and other necessary credentials.

Web Notifications

Setup Pusher in Laravel application

After completing the signup process, carefully note down all the credentials including API key, secret key and others. Then open SSH command interface and write down the following command:

Web Notifications Laravel

.env
Once the composer finishes its process, you can configure Laravel and Pusher. Open the .env file from the root directory of Laravel app and update its values to the desired ones.

// Get the credentials from your pusher dashboard
PUSHER_APP_ID=XXXXX
PUSHER_APP_KEY=XXXXXXX
PUSHER_APP_SECRET=XXXXXXX

Web Notifications Pusher

Create Notification Event

First of all, you must create an Event class that could broadcast to Pusher from your live Laravel application. Also remember that you can easily eradicate Events from anywhere in the application.

php artisan make:event Notification

The above-mentioned code will create a new Notification class in the app/Events directory. Open the contents of the file and update as shown below:

<?php

namespace App\Events;

use Illuminate\Queue\SerializesModels;
use Illuminate\Foundation\Events\Dispatchable;
use Illuminate\Broadcasting\InteractsWithSockets;
use Illuminate\Contracts\Broadcasting\ShouldBroadcast;

class Notification implements ShouldBroadcast{
    use Dispatchable, InteractsWithSockets, SerializesModels;
    public $username;
    public $message;

    public function __construct(){
        //your variables
    }

    public function broadcastOn(){
        return ['notification'];
    }
}

In the above-mentioned code, I have created a ShouldBroadcast interface which defines Laravel that the broadcasting of event should be with using whatever driver, which I have configured in the configuration file.

I have also created a constructor which accepts two parameters (username and verb). I have assigned these variables to class properties which also have the same name. Do remember to set the visibility of these properties to public, because they will be ignored if they aren’t set to public.

Lastly, I have set the channel name to broadcast on.

Create Controller

Now let’s create a controller, which will hold notification code logic. Open the SSH command terminal and paste the following command.

.$ php artisan make:controller PusherNotificationController

After successfully creating the controller, paste the following code in controller file.

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use Pusher\Pusher;

class PusherNotificationController 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 Cloudways";

        //Send a message to notify channel with an event name of notify-event
        $pusher->trigger('notification', 'notification-event', $message);
    }
}

It’s time to add Pusher in the controller. You will have to setup cluster and other credentials like secret key, API etc in your controller as well.

Afterwards, you can publish to a channel and can define a specific name for that channel. For this particular tutorial, I have given channel the name of ‘Notification’, and ‘Notification Event’ as the event name. You can also change these names to any other name according to your preference. Do remember to always use the same channel name and event name in your front end clients.

Setup Route

Now I will show you how to add notification route to the web.php file, which I will use to send notifications using Pusher.

//web.php

Route::get('/notification', 'PusherNotificationController@sendNotification');

Create View

Finally after setting up controller and required routes, now let’s move to create view. Working on welcome.blade.php, paste the below following code in your view file.

<!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 using Pusher In Laravel</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('notification');
        channel.bind('notification-event', function(message) {
            alert(message);
        });

    </script>
</body>
</html>

Now, let’s open up a new tab and visit www.yourdomain/notification while having the www.yourdomain.dev/welcome open in another tab and you should see the alert!.

To see the alert, open a new tab and visit www.yourdomain/notification while having the www.yourdomain.dev/welcome open on one tab. It will definitely show the alert and hence it will confirm the process mentioned in the preceding paragraphs.

Summing Up

In this blog, I have demonstrated how to implement real time notifications in a Laravel app using Pusher. Because Pusher allows us to add more live functionality to our apps and helps make it more interactive, popular social apps like Facebook and Twitter have live web notifications system integrated in their platform. Hence, using Pusher, we can also implement the same functionality in our apps and can enhance the real time interaction while using them.

If you still have more questions regarding this blog, or you want to contribute more on this topic, do feel free to share your thoughts and comments in the comments section below.

Author Info

Pradeep Kumar

Advertisement

4 responses to “Web Notifications Using Laravel and Pusher”

  1. Anoymouse says:

    Nice tutorial sir. But in my case is something like this.

    every time there’s an update(push event) of the repo from github a notication will be triggered for admin to notify for incoming webhook.

    Should I still used pusher or any third party to this? or I will just use guzzle and Laravel Notification?

    I already implemented guzzle and laravel notification but there are some problem. Like, if you refresh your dashboard the notification will trigger and will increment.

    I am new in Laravel and I hope you have suggestions in my case.

    Thanks and God bless.

    Anonymouse

  2. Ishrat Ali says:

    how to send notification to a specific user? can any body give a complete example please because i am also new in laravel.

  3. Mariana says:

    Sir thank you very much for this tutorial I have a question how can I keep my notifications because when k refresh the page notifications disappear

  4. topedpoker says:

    Ꮋello mates, its great post on the topioc oof edսcationand completely defined,
    keep it ᥙp all thhe time.

Leave a Reply

Your email address will not be published. Required fields are marked *