Laravel Real Time Notification Build with Pusher jQuery and Ajax
Hello dev
Let's check an example on laravel real time notification. This tutorial demonstrates the real time notification with the latest laravel and pusher. We also use Jquery and Ajax for building laravel real time notifcation system and counting the real time notification number. When an event fire the notification will send and count instantly. Here I will enter a text inside the input field and hit the send button then the notification will send without any delay. So follow the below steps carefully how we build the laravel real time notification system.
Technology used while writting the article. You can use any laravel versions.
PHP: 8.1
Laravel: 10.8
At first we have to register a pusher account to get the pusher credentials for our real time push notification app.
After complete the registration in pusher we will start the follow the below guidelines.
Step 1: Initialize Laravel App
Step 2: Install NPM Dependencies
Step 3 : Set Pusher Creadentials in .env
Step 4: Make an Event PushNotification
Step 5: Update web.php with Request Response and Event
Step 6: Update welcome.blade.php file
Step 7: Install Pusher Js and Server
Step 8: Update bootstrap.js
Step 9: Update app.js
Step 10: Enable BroadcastServiceProvider
Step 11: Test Application
Step 1: Initialize Laravel App
Execute the below code to install a fresh laravel project.
composer create-project laravel/laravel laravel-realtime-notification
Step 2: Install NPM Dependencies
Run the following command to install npm dependencies
npm install
Step 3 : Set Pusher Creadentials in .env
Update the env file with the pusher credentials and change BROADCAST_DRIVER=log to BROADCAST_DRIVER=pusher
.env
BROADCAST_DRIVER=pusher
PUSHER_APP_ID=your-pusher-app-id
PUSHER_APP_KEY=your-pusher-key
PUSHER_APP_SECRET=your-pusher-secret
PUSHER_HOST=
PUSHER_PORT=443
PUSHER_SCHEME=https
PUSHER_APP_CLUSTER=your-pusher-cluster
Step 4: Make an Event PushNotification
Now we will create an event with the help of artisan command. So run the following command to create the PushNotification event.
php artisan make:event PushNotification
Once the event successfully created we wil update the PushNotification class exactly like below. Here we will change the PrivateChannel into Channel inside the broadcastOn() method and channel name can be anything. We also create a method broadcastAs() and return the event name inside this method. We also initalize a public property $message and make a constructor to receive the input field values.
<?php
namespace App\Events;
use Illuminate\Broadcasting\Channel;
use Illuminate\Broadcasting\InteractsWithSockets;
use Illuminate\Broadcasting\PresenceChannel;
use Illuminate\Broadcasting\PrivateChannel;
use Illuminate\Contracts\Broadcasting\ShouldBroadcast;
use Illuminate\Foundation\Events\Dispatchable;
use Illuminate\Queue\SerializesModels;
class PushNotification implements ShouldBroadcast
{
use Dispatchable, InteractsWithSockets, SerializesModels;
public $message;
public function __construct($message)
{
$this->message = $message;
}
public function broadcastOn()
{
return new Channel('notification');
}
public function broadcastAs()
{
return 'PushNotification';
}
}
Step 5: Update web.php with Request Response and Event
Now update the web.php file with the given code.
web.php
<?php
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Route;
/*
|--------------------------------------------------------------------------
| Web Routes
|--------------------------------------------------------------------------
|
| Here is where you can register web routes for your application. These
| routes are loaded by the RouteServiceProvider and all of them will
| be assigned to the "web" middleware group. Make something great!
|
*/
Route::get('/', function () {
return view('welcome');
});
Route::post('send-notification',function (Request $request){
event(new \App\Events\PushNotification($request->message));
return ['success' => true];
});
Step 6: Update welcome.blade.php file
Here we will design our notification markup so that we can send and display the total notification number. We also link app.js and app.css using the vite directive. We use Bootstrap cdn link for desaign and notify icon as well as jQuery for fire an event. Finally must setup Ajax.
welcome.blade.php
<!doctype html>
<html lang="en">
<head>
<!-- Required meta tags -->
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<meta name="csrf-token" content="{{ csrf_token() }}">
<!-- Bootstrap CSS -->
<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.0.2/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-EVSTQN3/azprG1Anm3QDgpJLIm9Nao0Yz1ztcQTwFspd3yD65VohhpuuCOmLASjC" crossorigin="anonymous">
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap-icons@1.5.0/font/bootstrap-icons.css">
@vite(['resources/css/app.css' , 'resources/js/app.js'])
<title>Laravel Real Time Notification-WebJourney</title>
</head>
<body>
<div class="app">
<div class="row mt-5">
<div class="col-sm-4 offset-sm-4 text-center">
<span class="btn btn-danger my-3">
<i class="bi bi-bell"></i>
<span id="notification_count">0</span>
</span>
<div class="input-group">
<input type="text" name="message" id="message" placeholder="Enter Message" class="form-control">
</div>
<button type="submit" id="send_message" class="btn btn-primary btn-flat mt-3">Send Message</button>
</div>
</div>
</div>
<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.0.2/dist/js/bootstrap.bundle.min.js" integrity="sha384-MrcW6ZMFYlzcLA8Nl+NtUVF0sA7MsXsP1UyJoMp4YLEuNSfAP+JcXn/tWtIaxVXM" crossorigin="anonymous"></script>
<script src ="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
<script>
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
</script>
</body>
</html>
Step 7: Install Pusher Js and Server
In this step we need to install pusher js and php pusher server. so install both of these execute the below two command.
npm install --save laravel-echo pusher-js
composer require pusher/pusher-php-server
Step 8: Update bootstrap.js
Now update the file with the given code.
resources/js/bootstrap.js
/**
* We'll load the axios HTTP library which allows us to easily issue requests
* to our Laravel back-end. This library automatically handles sending the
* CSRF token as a header based on the value of the "XSRF" token cookie.
*/
import axios from 'axios';
window.axios = axios;
window.axios.defaults.headers.common['X-Requested-With'] = 'XMLHttpRequest';
/**
* Echo exposes an expressive API for subscribing to channels and listening
* for events that are broadcast by Laravel. Echo and event broadcasting
* allows your team to easily build robust real-time web applications.
*/
// import Echo from 'laravel-echo';
// import Pusher from 'pusher-js';
// window.Pusher = Pusher;
// window.Echo = new Echo({
// broadcaster: 'pusher',
// key: import.meta.env.VITE_PUSHER_APP_KEY,
// cluster: import.meta.env.VITE_PUSHER_APP_CLUSTER ?? 'mt1',
// wsHost: import.meta.env.VITE_PUSHER_HOST ? import.meta.env.VITE_PUSHER_HOST : `ws-${import.meta.env.VITE_PUSHER_APP_CLUSTER}.pusher.com`,
// wsPort: import.meta.env.VITE_PUSHER_PORT ?? 80,
// wssPort: import.meta.env.VITE_PUSHER_PORT ?? 443,
// forceTLS: (import.meta.env.VITE_PUSHER_SCHEME ?? 'https') === 'https',
// enabledTransports: ['ws', 'wss'],
// });
import Echo from 'laravel-echo';
import Pusher from 'pusher-js';
window.Pusher = Pusher;
window.Echo = new Echo({
broadcaster: 'pusher',
key: import.meta.env.VITE_PUSHER_APP_KEY,
cluster: import.meta.env.VITE_PUSHER_APP_CLUSTER,
forceTLS: true
});
Step 9: Update app.js
Inside this file we will write jQuery and ajax code to fire an event and send notification request also display the total notification count. So update the file like below.
import './bootstrap';
$(document).ready(function(){
$(document).on('click','#send_message',function (e){
e.preventDefault();
let message = $('#message').val();
if(message == ''){
alert('Please enter message')
return false;
}
$.ajax({
method:'post',
url:'/send-notification',
data:{message:message},
success:function(res){
$('#notification_count').val()
$('#notification_count').text( parseInt($('#notification_count').text()) + 1 );
$('#message').val('');
}
});
});
});
window.Echo.channel('chat')
.listen('.PushNotification',(e)=>{
$('#message').val('');
});
Step 10: Enable BroadcastServiceProvider
Finally uncomment the BroadcastServiceProvider to enable it.
'providers' => ServiceProvider::defaultProviders()->merge([
/*
* Package Service Providers...
*/
/*
* Application Service Providers...
*/
App\Providers\AppServiceProvider::class,
App\Providers\AuthServiceProvider::class,
App\Providers\BroadcastServiceProvider::class,
App\Providers\EventServiceProvider::class,
App\Providers\RouteServiceProvider::class,
])->toArray(),
Step 11: Test Application
Everything is done. For send a real time notification run the below two cammands in two different terminal.
npm run dev
php artisan serve
Output:
If you like what you are reading, please think about buying us a coffee as a token of appreciation.
We appreciate your support and are committed to providing you useful and informative content.
We are thankful for your ongoing support
You May Like These:
Laravel pusher real time chat application build with javaScript jQuery