Laravel

Web Push Notifications Using Laravel and Pusher

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 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 project
  • 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.

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:

.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
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 Codehunger";

        //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.

Afterward, 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.


Conclusion

In this blog, I have explained 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. Thanks

Related Articles

Leave a Reply

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

Back to top button