Laravel Php

How To Create Web Push Notification Using Laravel And Pusher

How To Create Web Push Notification Using Laravel And Pusher

When We are building a web Application. In web Application’s Notifications play a very important role. Every Web app want a quick notification, whenever any event is fired. For Example On facebook or Instagram, User will be notified when someone likes or comment on your post . We will impliment this feature in this tutorial by web notification system using Laravel and Pusher.

What we are building today

In this tutorial , we will see a small demonstrate that how we can show realtime notification using laravel and Pusher. It would be similar to facebook notification. Here is a preview of what we would be building.

Setting pusher app details

Create a Pusher account, if you have already an account , then set up your application as seen in the screenshot below.

Setting up Our Laravel application

You can create a new Laravel application by running the command below in your terminal or you can choose any other method depends on you:

composer create-project --prefer-dist laravel/laravel blog

After setting laravel project, we need to install Pusher package or sdk in our laravel project. We can install this using composer:

composer require pusher/pusher-php-server

After installing Pusher SDk, we need to configure our laravel application to use the pusher as the its broadcast driver.To do this, we need to make changes in our .env file. This file is available at the root of the laravel installation directory. Update the following details as given below:

// Get the credentials from your pusher App dashboard

Enable The Broadcasting service

Open config/app.php and uncomment the App\Providers\BroadcastServiceProvider::class

Creating our Laravel and Pusher application

Now We are done with the laravel and pusher configuration, Let’s create our application. First we would create and Event class that would broadcast to pusher from pur application. Event can be fired from anywher in our application.

php artisan make:event StatusLiked

This will create a new StatusLiked class in the app/Events directory. Open the contents of the file and update to the following below:

namespace App\Events;
use Illuminate\Broadcasting\Channel;
use Illuminate\Queue\SerializesModels;
use Illuminate\Broadcasting\PrivateChannel;
use Illuminate\Broadcasting\PresenceChannel;
use Illuminate\Foundation\Events\Dispatchable;
use Illuminate\Broadcasting\InteractsWithSockets;
use Illuminate\Contracts\Broadcasting\ShouldBroadcast;
class StatusLiked implements ShouldBroadcast
    use Dispatchable, InteractsWithSockets, SerializesModels;
    public $username;
    public $message;
     * Create a new event instance.
     * @return void
    public function __construct($username)
        $this->username = $username;
        $this->message  = "{$username} liked your status";
     * Get the channels the event should broadcast on.
     * @return Channel|array
    public function broadcastOn()
        return ['status-liked'];

Above, we have implemented the ShouldBroadcast interface and this tells Laravel that this event should be broadcasted using whatever driver we have set in the configuration file.
We also have a constructor that accepts two parameters, username and verb. We will get back to this later on. We assigned these variables to class properties named the same way. It is important to set the visibility of the properties to public; if you don’t, the property will be ignored.
Lastly, we set the channel name to broadcast on.

Creating the application views

We will keep it simple and create a single view where you can see a navigation bar with a notification icon. The icon will be updated when new notifications are available without the need to refresh the page. The notifications are ephemeral in this tutorial by design; you can extend the functionality and make it last longer after the page reloads if you so desire.
Open the welcome.blade.php file and replace it with the HTML below.

r<!DOCTYPE html>
<html lang="en">
    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <link rel="stylesheet" href="//" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous">
    <link rel="stylesheet" type="text/css" href="/css/bootstrap-notifications.min.css">
    <!--[if lt IE 9]>
      <script src=""></script>
      <script src=""></script>
    <nav class="navbar ">
      <div class="container-fluid">
        <div class="navbar-header">
          <button type="button" class="navbar-toggle collapsed" data-toggle="collapse" data-target="#bs-example-navbar-collapse-9" aria-expanded="false">
            <span class="sr-only">Toggle navigation</span>
            <span class="icon-bar"></span>
            <span class="icon-bar"></span>
            <span class="icon-bar"></span>
          <a class="navbar-brand" href="#">TemplateBench</a>
        <div class="collapse navbar-collapse">
          <ul class="nav navbar-nav">
            <li class="dropdown dropdown-notifications pull-right">
              <a href="#notifications-panel" class="dropdown-toggle" data-toggle="dropdown">
                <i data-count="0" class="glyphicon glyphicon-bell notification-icon"></i>
              <div class="dropdown-container ">
                <div class="dropdown-toolbar">
                  <div class="dropdown-toolbar-actions">
                    <a href="#">Mark all as read</a>
                  <h3 class="dropdown-toolbar-title">Notifications (<span class="notif-count">0</span>)</h3>
                <ul class="dropdown-menu">
                <div class="dropdown-footer text-center">
                  <a href="#">View All</a>
            <li><a href="#">Timeline</a></li>
            <li><a href="#">Friends</a></li>
    <script src="//"></script>
    <script src="//"></script>
    <script src="//" integrity="sha384-Tc5IQib027qvyjSMfHjOMaLkfuWVxZxUPnCJA7l2mCWNIpG9mGCD8wGNIcPD7Txa" crossorigin="anonymous"></script>
    <script type="text/javascript">
      var notificationsWrapper   = $('.dropdown-notifications');
      var notificationsToggle    = notificationsWrapper.find('a[data-toggle]');
      var notificationsCountElem = notificationsToggle.find('i[data-count]');
      var notificationsCount     = parseInt('count'));
      var notifications          = notificationsWrapper.find('ul.dropdown-menu');
      if (notificationsCount <= 0) {
      // Enable pusher logging - don't include this in production
      // Pusher.logToConsole = true;
      var pusher = new Pusher('your-api-key', {
        broadcaster: 'pusher',
        cluster: 'your-cluster',
        encrypted: true
      // Subscribe to the channel we specified in our Laravel Event
      var channel = pusher.subscribe('status-liked');
      // Bind a function to a Event (the full Laravel class)
      channel.bind('App\\Events\\StatusLiked', function(data) {
        var existingNotifications = notifications.html();
        var avatar = Math.floor(Math.random() * (71 - 20 + 1)) + 20;
        var newNotificationHtml = `
          <li class="notification active">
              <div class="media">
                <div class="media-left">
                  <div class="media-object">
                    <img src="`+avatar+`.png" class="img-circle" alt="50x50" style="width: 50px; height: 50px;">
                <div class="media-body">
                  <strong class="notification-title">`+data.message+`</strong>
                  <!--p class="notification-desc">Extra description can go here</p-->
                  <div class="notification-meta">
                    <small class="timestamp">about a minute ago</small>
        notifications.html(newNotificationHtml + existingNotifications);
        notificationsCount += 1;
        notificationsCountElem.attr('data-count', notificationsCount);

his is mostly a lot of Bootstrap noise so we will isolate the important parts, mostly Javascript. We include the Pusher javascript library, and then we added the javascript block that does the magic. Let us look at some snippets of the javascript block:

// Enable pusher logging - don't include this in production
// Pusher.logToConsole = true;
// Initiate the Pusher JS library
var pusher = new Pusher('API_KEY_HERE', {
    encrypted: true
// Subscribe to the channel we specified in our Laravel Event
var channel = pusher.subscribe('status-liked');
// Bind a function to a Event (the full Laravel class)
channel.bind('App\\Events\\StatusLiked', function(data) {
    // this is called when the event notification is received...

The code above just initializes the Pusher JS library and subscribes to a channel. It then sets a callback to call when the event broadcasted is received on that channel.

Testing our set up

Finally to test our set up, we will create a route that manually calls the event. If everything works as expected, we will get a new notification anytime we hit the route. Let’s add the new route:

Route::get('test', function () {
    event(new App\Events\StatusLiked('Someone'));
    return "Event has been sent!";

Now we can start a PHP server using Laravel so we can test our code to see if it works.

$ php artisan serve


In this article we have been able to leverage the power of Pusher to create a modern web notifications system and it was very easy. This is just scratching the surface of what can be really done using Pusher. The example was just to show you the possibilities.
You can get the full source code from Github.
I hope this code is helpfull to You. if you like this post than don’t forget to share with your friends.
You can also like our facebook page (TemplateBench) for future posts updates.

Related posts

Laravel custom 404 page


Laravel Arrays & Objects helper


Laravel 5.5 introduces new Route Methods


1 comment

Sangeet kumar February 1, 2018 at 5:57 pm

Thanks sir ji


Leave a Comment