向特定用户发送推送通知 - Laravel
send pusher notification to specific user - Laravel
在我的 laravel 应用中,我想使用 Pusher 向特定用户发送通知。
我将此代码放入我的方法中:
$pusher = App::make('pusher');
$pusher->trigger( 'notification-channel',
'notification-event',
array('text' => 'this is a notification'));
return view('home');
并将其放入 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);
});
但这会使通知显示给任何用户。
这还有一个问题就是用户应该只能在主页上才能收到通知!
那么,我应该怎么做才能向特定用户发送通知并让该用户从任何页面接收通知??
要让用户从任何页面接收它,请将您的 Pusher 代码放入 layout.blade.php
(如果有)。或所有页面将扩展的任何其他文件。
要使其转到特定用户,您可以通过将用户 ID 附加到频道来使用用户 ID,例如
'notification-channel:' . $user->id
因此在您的布局文件中您收听该频道
var user = <?php echo $user ; ?>;
var channel = pusher.subscribe('notification-channel:' + user.id);
虽然只有具有这种简单性的用户可能会收到通知,但您的通知仍然存在 public。这意味着任何人都可以操纵他们的 ID 并接收其他人的通知。如果您想要私人通知,可以按照此处的说明进行操作:https://laravel.com/docs/5.4/broadcasting#authorizing-channels
在我的 laravel 应用中,我想使用 Pusher 向特定用户发送通知。
我将此代码放入我的方法中:
$pusher = App::make('pusher');
$pusher->trigger( 'notification-channel',
'notification-event',
array('text' => 'this is a notification'));
return view('home');
并将其放入 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);
});
但这会使通知显示给任何用户。 这还有一个问题就是用户应该只能在主页上才能收到通知!
那么,我应该怎么做才能向特定用户发送通知并让该用户从任何页面接收通知??
要让用户从任何页面接收它,请将您的 Pusher 代码放入 layout.blade.php
(如果有)。或所有页面将扩展的任何其他文件。
要使其转到特定用户,您可以通过将用户 ID 附加到频道来使用用户 ID,例如
'notification-channel:' . $user->id
因此在您的布局文件中您收听该频道
var user = <?php echo $user ; ?>;
var channel = pusher.subscribe('notification-channel:' + user.id);
虽然只有具有这种简单性的用户可能会收到通知,但您的通知仍然存在 public。这意味着任何人都可以操纵他们的 ID 并接收其他人的通知。如果您想要私人通知,可以按照此处的说明进行操作:https://laravel.com/docs/5.4/broadcasting#authorizing-channels