Laravel Real Time Notification Tutorial With Example

Hello developers, In this example, I will explain to you how to do Laravel Real Time Notification Tutorial With Example. We use pusher for real-time notification. Pusher is one of the most famous services which supports you deliver real-time notifications to your applicationsWhen creating web applications, it is not uncommon to see some in-app notification system that will notify you immediately when someone carries out an action related to you or your account.

Laravel Real Time Notification Tutorial With Example

We are going to Configure Laravel Project.

#1: Download Laravel Project

Establish  Laravel Project by the typing following command.

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

#2: Install pusher-php-server Package

First, install pusher-php-server via the Composer package manager.

composer require pusher/pusher-php-server

The package will automatically register itself.

#3: Setup Pusher Application

Next, Sign up for a new account on Pusher.com, if you have already an account then sign in. Your application as viewed in the screenshot below.

laravel real time notification example

You can get your app_id, key, secret and also note down your cluster. These can be located in the App Keys section of your Pusher dashboard. You can also see below image for more clarification.

real time notification laravel pusher

We will want to configure Laravel to use Pusher as its broadcast driver, to do this, open the.env file and Update the values to correspond to the configuration below:

//.env

PUSHER_APP_ID=xxxxx
PUSHER_APP_KEY=xxxxx
PUSHER_APP_SECRET=xxxxx
PUSHER_APP_CLUSTER=xxxxx

#4: Create an event

First, we create an event class that would broadcast to Pusher from our Laravel project. Events can be fired from everywhere in the application.

php artisan make:event Notify

This will create a new Notify class in the app >> Events directory. Open the contents of the file and change to the below:

//Notify.php

<?php

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 Notify
{
    use Dispatchable, InteractsWithSockets, SerializesModels;

    /**
     * Create a new event instance.
     *
     * @return void
     */
    public function __construct()
    {
        //
    }

    /**
     * Get the channels the event should broadcast on.
     *
     * @return \Illuminate\Broadcasting\Channel|array
     */
    public function broadcastOn()
    {
        return new PrivateChannel('notify-channel');
    }
}

#5: Create a Controller

php artisan make:controller NotificationController

It will build a controller file called NotificationController.php.

Add following code to the controller.

//NotificationController.php

<?php

namespace App\Http\Controllers;

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

class NotificationController extends Controller
{
    public function notify()
    {
        $options = array(
                        'cluster' => env('PUSHER_APP_CLUSTER'),
                        'encrypted' => true
                        );
        $pusher = new Pusher(
                            env('PUSHER_APP_KEY'),
                            env('PUSHER_APP_SECRET'),
                            env('PUSHER_APP_ID'), 
                            $options
                        );

        $data['message'] = 'hello investmentnovel';
        $pusher->trigger('notify-channel', 'App\\Events\\Notify', $data);

    }
}
  • Here we first include Pusher in our Notificationcontroller and set cluster and encrypted in the options array. We later create a new Pusher object by defining our credentials and also passing in the $options array.
  • We can publish to a channel and also specify a channel name. I have used notify-channel as the channel name and notify as the event name and those can be modified to any name you want. But don’t forget to use the same channel name and event name in your front-end.

#6: Define Route

We register all route in a web.php file.

//web.php

Route::get('notify','NotificationController@notify');
Route::view('/notification', 'notification');

#7: Create a View File

Create a file in resources/ views/notification.blade.php and put this following code in it.

<!-- notification.blade.php --> 

<!DOCTYPE html>
<head>
  <title>Laravel Real Time Notification Tutorial With Example</title>
  <h1>Laravel Real Time Notification Tutorial With Example</h1>
  <script src="https://js.pusher.com/4.1/pusher.min.js"></script>
  <script>

   var pusher = new Pusher('{{env("MIX_PUSHER_APP_KEY")}}', {
      cluster: '{{env("PUSHER_APP_CLUSTER")}}',
      encrypted: true
    });

    var channel = pusher.subscribe('notify-channel');
    channel.bind('App\\Events\\Notify', function(data) {
      alert(data.message);
    });
  </script>
</head>

Next, Open a new tab and visit  http://localhost:8000/notify while having the  http://localhost:8000/notification open in another tab and you should see the notification.

Laravel Real Time Notification Using Pusher

At last, our Laravel Real Time Notification Tutorial With Example is over.

Post Your Thoughts

This site uses Akismet to reduce spam. Learn how your comment data is processed.

One Response