Search code examples
phplaravelpush-notificationbroadcastingpusher-js

Bind Real Time Notifications in Laravel Blade as alert


In my web app I want to notify some specific users when some task is created from admin. This should be real time. Therefore I used laravel pusher. But it not make any sense. I want to fix this.

My Controller :

        public function add(Request $request){
            $data = $request->all();
            $tasks = Todo::create($data);

            //send notofications 
            $notifyTo = User::whereHas('roles', function($q){$q->whereIn('slug', [ 'manager'   ]);})->get();
            foreach ($notifyTo as $notifyUser) {
                $notifyUser->notify(new TaskCreated($tasks));
            }
        }

My TaskCreated Notification Class

public function via($notifiable)
   {
      return ['broadcast'];
   }

public function toBroadcast($notifiable)
{
    return [
        'title' => $this->tasks->task
    ];
}

My Pusher Debug Console

Pusher Debug Console

This is my boostrap.js

/**
 * 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'

window.Pusher = require('pusher-js');

window.Echo = new Echo({
    broadcaster: 'pusher',
    key:'bf6e79cce8gfggf548fb2c5e9',
    cluster: 'ap2',
    forceTLS: true
});

and this is my front end

<script>
  var userId = $('meta[name="userId"]').attr('content');
    Echo.private('App.User.' + userId)
    .notification((notification) => {
        console.log(notification.type);
    });

  </script>

Config/broadcasting.php

<?php

return [

    /*
    |--------------------------------------------------------------------------
    | Default Broadcaster
    |--------------------------------------------------------------------------
    |
    | This option controls the default broadcaster that will be used by the
    | framework when an event needs to be broadcast. You may set this to
    | any of the connections defined in the "connections" array below.
    |
    | Supported: "pusher", "redis", "log", "null"
    |
    */

    'default' => env('BROADCAST_DRIVER', 'null'),

    /*
    |--------------------------------------------------------------------------
    | Broadcast Connections
    |--------------------------------------------------------------------------
    |
    | Here you may define all of the broadcast connections that will be used
    | to broadcast events to other systems or over websockets. Samples of
    | each available type of connection are provided inside this array.
    |
    */

    'connections' => [

        'pusher' => [
            'driver' => 'pusher',
            'key' => env('PUSHER_APP_KEY'),
            'secret' => env('PUSHER_APP_SECRET'),
            'app_id' => env('PUSHER_APP_ID'),
            //'options' => [
                //'cluster' => env('PUSHER_APP_CLUSTER'),
                //'encrypted' => true,
               // 'host' => '127.0.0.1',
               // 'port' => 6004,
               // 'scheme' => 'http'
            //],

            'options' => [
                'cluster' => 'ap2',
                'useTLS' => true
            ],
        ],

        'redis' => [
            'driver' => 'redis',
            'connection' => 'default',
        ],

        'log' => [
            'driver' => 'log',
        ],

        'null' => [
            'driver' => 'null',
        ],

    ],

];

I want to alert title of notification in my laravel web app. How can it possible ? Please suggest a solution for front end.


Solution

  • You need to use the Notifiable trait in User model. After that, you need to specify what channel the broadcast will use. To make it unique, append user_id at the end of a constant channel_name like so:

    class User extends Authenticatable
    {
        use Notifiable;
    
        /**
         * The channels the user receives notification broadcasts on.
         *
         * @return string
         */
        public function receivesBroadcastNotificationsOn()
        {
            return 'users.'.$this->id;
        }
    }
    

    On the frontend, you need to use a package called Laravel Echo. You can listen to your broadcasts on the front end using the Laravel Echo like so:

    Echo.private('users.' + userId)
        .notification((notification) => {
            console.log(notification.type);
        });
    

    Reference Docs: https://laravel.com/docs/7.x/notifications#listening-for-notifications