【发布时间】:2020-01-06 00:23:12
【问题描述】:
我刚开始使用laravel broadcasting 并遇到了一个问题。我正在使用 Pusher,我想检查用户是否有权订阅私人频道。用户对帖子的评论通知的访问是经过身份验证但未授权的。我正在尝试仅向帖子的作者发送新评论的通知,但所有打开帖子的经过身份验证的用户都会收到通知。我错过了什么还是什么?
<?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 NewCommentEvent implements ShouldBroadcast
{
use Dispatchable, InteractsWithSockets, SerializesModels;
/**
* Create a new event instance.
*
* @return void
*/
public $comment;
public function __construct($comment)
{
$this->comment = $comment;
}
/**
* Get the channels the event should broadcast on.
*
* @return \Illuminate\Broadcasting\Channel|array
*/
public function broadcastOn()
{
return new PrivateChannel('post-'.$this->comment->post_id);
}
public function broadcastAs()
{
return 'new-comment-event';
}
public function broadcastWith()
{
return ['comment' => $this->comment->comment];
}
}
routes/channel.php:
<?php
use App\models\Post;
Broadcast::channel('App.User.{id}', function ($user, $id) {
return (int) $user->id === (int) $id;
});
Broadcast::channel('post-{id}', function ($user, $id) {
return false;
//return $user->id == Post::find($id)->author_id;
});
可见的 JavaScript:
var pusher = new Pusher('904d58ankty8c8397d000', {
authEndpoint: 'http://localhost/blog/public/broadcasting/auth',
cluster: 'ap2',
forceTLS: true,
auth: {
headers: {
'X-CSRF-Token': "{{csrf_token()}}"
}
}
});
var privateChannel = pusher.subscribe("private-post-{{{$post->id}}}");
privateChannel.bind('new-comment-event', function(data) {
$('#post-comments').append('<p>'+data.comment+'</p>');
});
顺便说一下以下是提供者代码:
public function boot()
{
Broadcast::routes(['middleware' => ['auth']]);
require base_path('routes/channels.php');
}
我使用的laravel版本是:5.8
【问题讨论】:
-
似乎根本没有调用channel.php路由。