Table of Contents

How to Create Real Time Notification in Laravel 10 using Pusher

  • Mar-06-2024
  • Techsolutionstuff

  • Laravel

In this tutorial, I’ll guide you through the process of adding real-time notifications to your Laravel 10 projects using Pusher. Here, we’ll learn about how to create real-time push notifications in laravel 10 and laravel 11.

Real-time notifications are awesome because they keep your users up-to-date with important updates instantly, no need for them to constantly refresh the page.

So, let’s see to implementing push notifications in your Laravel 9/10/11 applications.

Step 1: Set Up Your Laravel Project

Create a new Laravel project if you haven’t already using laravel new project-name.

laravel new laravel-web-notifications

 

Step 2: Install Pusher Package

Install the Pusher PHP SDK using Composer by running:

composer require pusher/pusher-php-server

Sign up for a free account on the Pusher website. Create a new app in your Pusher dashboard. Note down your Pusher app credentials (app ID, key, secret).

 

Step 3: Configure Laravel with Pusher

Open your Laravel project and locate the .env file. Add your Pusher credentials to the .env file:

PUSHER_APP_ID=your-app-id
PUSHER_APP_KEY=your-app-key
PUSHER_APP_SECRET=your-app-secret
PUSHER_APP_CLUSTER=your-app-cluster

Note: If you’re using the EU or AP Cluster, make sure to update the options array in your config/broadcasting.php config since Laravel defaults to using the US Server.

 

Step 4: Create a Notification Event

Generate a new notification using Laravel’s Artisan command:

php artisan make:event StatusLiked

Open the StatusLiked class in the app/Events directory.

<?php

namespace App\Events;

use Illuminate\Queue\SerializesModels;
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'];
	}
}

The ShouldBroadcast interface tells Laravel that this event should be broadcast using whatever driver is set in the configuration file.

 

Step 5: Creating the application views

Open the welcome.blade.php file and replace it with the HTML below.

<!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>How to Create Real Time Notification in Laravel 10 using Pusher - Techsolutionstuff</title>
	<link rel="stylesheet" href="//maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
	<link rel="stylesheet" type="text/css" href="/css/bootstrap-notifications.min.css">	
  </head>
  <body>
	<nav class="navbar navbar-inverse">
	  <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>
		  </button>
		  <a class="navbar-brand" href="#">How to Create Real Time Notification in Laravel 10 using Pusher - Techsolutionstuff</a>
		</div>

		<div class="collapse navbar-collapse">
		  <ul class="nav navbar-nav">
			<li class="dropdown dropdown-notifications">
			  <a href="#notifications-panel" class="dropdown-toggle" data-toggle="dropdown">
				<i data-count="0" class="glyphicon glyphicon-bell notification-icon"></i>
			  </a>

			  <div class="dropdown-container">
				<div class="dropdown-toolbar">
				  <div class="dropdown-toolbar-actions">
					<a href="#">Mark all as read</a>
				  </div>
				  <h3 class="dropdown-toolbar-title">Notifications (<span class="notif-count">0</span>)</h3>
				</div>
				<ul class="dropdown-menu">
				</ul>
				<div class="dropdown-footer text-center">
				  <a href="#">View All</a>
				</div>
			  </div>
			</li>
			<li><a href="#">Timeline</a></li>
			<li><a href="#">Friends</a></li>
		  </ul>
		</div>
	  </div>
	</nav>

	<script src="//cdnjs.cloudflare.com/ajax/libs/jquery/2.1.4/jquery.min.js"></script>
	<script src="//js.pusher.com/3.1/pusher.min.js"></script>
	<script src="//maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></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(notificationsCountElem.data('count'));
	  var notifications          = notificationsWrapper.find('ul.dropdown-menu');

	  if (notificationsCount <= 0) {
		notificationsWrapper.hide();
	  }

	  // Enable pusher logging - don't include this in production
	  // Pusher.logToConsole = true;

	  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) {
		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="https://api.adorable.io/avatars/71/`+avatar+`.png" class="img-circle" alt="50x50" style="width: 50px; height: 50px;">
				  </div>
				</div>
				<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>
				  </div>
				</div>
			  </div>
		  </li>
		`;
		notifications.html(newNotificationHtml + existingNotifications);

		notificationsCount += 1;
		notificationsCountElem.attr('data-count', notificationsCount);
		notificationsWrapper.find('.notif-count').text(notificationsCount);
		notificationsWrapper.show();
	  });
	</script>
  </body>
</html>

The Pusher javascript library is included, and then the javascript block that pushes notifications. These are the important snippets in 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...
});

Note: By default, Laravel will broadcast the event using the event’s class name. However, you may customize the broadcast name by defining a broadcast as a method of the event:

public function broadcastAs() {
  return 'event-name';
}

 

Step 6: Test Your Application

Run your Laravel application using Create an Event.

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

Now start a PHP server using Laravel command.

$ php artisan serve

And there you have it! You’ve successfully implemented real-time notifications in your Laravel 10 application using Pusher.

 


You might also like:

techsolutionstuff

Techsolutionstuff | The Complete Guide

I’m a software engineer and the founder of techsolutionstuff.com. Hailing from India, I craft articles, tutorials, tricks, and tips to aid developers. Explore Laravel, PHP, MySQL, jQuery, Bootstrap, Node.js, Vue.js, and AngularJS in our tech stack.

RECOMMENDED POSTS

FEATURE POSTS


















SUBSCRIBE YOUR EMAIL ADDRESS



Categorized in:

Uncategorized,