如何将事件发送给特定用户? (laravel 5.3)

时间:2017-03-26 04:49:24

标签: php laravel events laravel-5 laravel-5.3

我正在与laravel和pusher进行一对一的聊天。我正在尝试将事件仅发送给正在谈话的人但不能这样做。事件发送给所有人,不知道是什么这个问题。

<ul class="list" id="friend">
      @foreach(Auth::user()->friends() as $f)
        <li  data-friend="{{$f->id}}" class="clearfix" style="cursor: pointer">
          <img src="https://s3-us-west-2.amazonaws.com/s.cdpn.io/195612/chat_avatar_01.jpg" alt="avatar" />
          <div class="about">
            <div class="name">{{$f->firstname}}</div>
            <div class="status">
              <i class="fa fa-circle online"></i> online
            </div>
          </div>
        </li>
        @endforeach
      </ul>

textarea的:

<div class="chat-message clearfix">
        <textarea name="message-to-send" id="message-to-send" placeholder ="Type your message" rows="3"></textarea>

        <i class="fa fa-file-o"></i> &nbsp;&nbsp;&nbsp;
        <i class="fa fa-file-image-o"></i>

        <button id="send" data-userid="{{Auth::user()->id}}">Send</button>

      </div>

脚本:

<script>
      b={!!json_encode(Auth::user()->id)!!};
     pusher=new Pusher('******',{
    cluster:'ap1'
   });
  channel=pusher.subscribe('user'+b);

    $(document).ready(function(){
   $('#friend li').click(function(){
   var f=$(this).attr('data-friend');
    $('#send').click(function(){
    var userid=$(this).attr('data-userid');
    var message=$('#message-to-send').val();

      $.ajax({
        method:'GET',
        url:'/chat2/'+message+'/'+f,
        success:function(response){
          console.log('dshfgjhgdhjs');
        }
      })
  });
});
 });
     channel.bind('App\\Events\\chat2', function(e){
      console.log(e);
     } );
  </script>

路线:

Route::get('/chat2/{message}/{friend}',function($message,$friend){

     event(new chat2(Auth::user(),$message,$friend));

});

事件:

class chat2 implements ShouldBroadcast
{
    use InteractsWithSockets, SerializesModels;

    public $user;
    public $message;
    public $friend;
    /**
     * Create a new event instance.
     *
     * @return void
     */
    public function __construct(User $user,$message,$friend)
    {
        $this->user=$user;
        $this->message=$message;
        $this->friend=$friend;//
    }

    /**
     * Get the channels the event should broadcast on.
     *
     * @return Channel|array
     */
    public function broadcastOn()
    {
        return new Channel('user'.$this->friend);
    }
}

1 个答案:

答案 0 :(得分:1)

您需要查看私人广播频道。 Laravel支持经过身份验证的私有频道用于广播事件。

https://laravel.com/docs/5.4/broadcasting#authorizing-channels

让用户收听私人频道后,您只能向该频道发送活动。