Rowayda Khayri
Rowayda Khayri

Reputation: 489

send pusher notification to specific user - Laravel

In my laravel app, I want to send a notification to a specific user using Pusher.

I put this code in my method :

$pusher = App::make('pusher');

$pusher->trigger( 'notification-channel',
                  'notification-event', 
                   array('text' => 'this is a notification'));

return view('home');

and put this in home.blade.php :

<script src="//js.pusher.com/3.0/pusher.min.js"></script>
<script>

    var pusher = new Pusher("{{env("PUSHER_KEY")}}");
    var channel = pusher.subscribe('notification-channel');
    channel.bind('notification-event', function(data) {
      alert(data.text);
    });

but this makes notification to appear to any user. This also has another problem that the user should be only on the home page to receive the notification!

So, what should I do to send a notification to a specific user and make the user receive it from any page ??

Upvotes: 3

Views: 8605

Answers (1)

EddyTheDove
EddyTheDove

Reputation: 13259

To make the user receive it from any page, put your Pusher code in your layout.blade.php if you have any. Or any other file that all pages will extends.

To make it go to a specific user, you can use the user id by appending it to the channel like

'notification-channel:' . $user->id

So in your layout file you listen to that channel

var user = <?php echo $user ; ?>;
var channel = pusher.subscribe('notification-channel:' + user.id);

Although only user with that easy might receive the notification, your notification remains public. Meaning anyone can manipulate their id and receive someone else notifications. If you want private notifications, you can follow instructions here: https://laravel.com/docs/5.4/broadcasting#authorizing-channels

Upvotes: 9

Related Questions