使用pusher在laravel和vue js中实时聊天?

时间:2018-01-12 07:33:04

标签: laravel-5 vuejs2 real-time pusher pusher-js

大家好请指导我如何在实时聊天系统中使用pusher。推送器已安装在我的应用程序中并正在进行实时通知,但我想在我的消息中添加推送器。我的消息系统工作正常。请在此处添加推送代码。如果它需要广播事件或通知你可以告诉我bcz我有这个概念。我应该在事件中添加什么等。但我没有推动者的概念。 这是vue js文件代码。

`data:{ msg: 'my new msg', content: '', privsteMsgs: [], singleMsgs:[], msgFrom: '', conID: '', friend_id: '', seen: false, newMsgFrom: ''`

ready: function(){
    this.created();

},
created(){
    axios.get('http://localhost:8000/getMessages')
        .then(response => {
        console.log(response.data); // show if success
    app.privsteMsgs = response.data; //we are putting data into our posts array
})
.catch(function (error) {
        console.log(error); // run if we have error
    });
},
methods:{
    message: function(id){
       // alert(id);

        axios.get('http://localhost:8000/getMessages' +id)
            .then(response => {
            console.log(response.data); // show if success
        app.singleMsgs = response.data;
        app.conID = response.data[0].conversation_id;
    })
        .catch(function (error) {
            console.log(error); // run if we have error
        });

    },

    inputHandler(e){
        if(e.keyCode===13 && !e.shiftKey){
            e.preventDefault();
            this.sendMsg();
        }
    },
    sendMsg(){
        if(this.msgFrom){
          //  alert(this.conID);
           // alert(this.msgFrom);

            axios.post('http://localhost:8000/sendMessage', {
                conID: this.conID,
                msg: this.msgFrom
            })

                .then( (response) => {
              //  console.log('save Successfully');
                console.log(response.data); // show if success



            if(response.status===200){
                console.log('save Successfully')
               // console.log('save Successfully'+ data);
                 app.singleMsgs = response.data;
                app.msgFrom= '';

              // /  app.conID = response.data[0].conversation_id;
            }

        })
        .catch(function (error) {
                console.log(error); // run if we have error
            });


        }
    },
    friendID: function(id){
        app.friend_id = id;
    },
    sendNewMsg(){
        axios.post('http://localhost:8000/sendNewMessage', {
            friend_id: this.friend_id,
            msg: this.newMsgFrom,
        })
            .then(function (response) {
                console.log(response.data); // show if success
                if(response.status===200){
                    window.location.replace('http://localhost:8000/messages');
                    app.msg = 'your message has been sent successfully';
                }

            })
            .catch(function (error) {
                console.log(error); // run if we have error
            });
    }



}

这些是路线

Route::get('/messages', function () {
return view('messages');

}); Route :: get(' / getMessages',function(){

$allUsers1 = DB::table('users')
    ->Join('conversations','users.id','conversations.user_one')
    ->where('conversations.user_two', Auth::user()->id)->get();


$allUsers2 = DB::table('users')
    ->Join('conversations','users.id','conversations.user_two')
    ->where('conversations.user_one', Auth::user()->id)->get();
return array_merge($allUsers1->toArray(), $allUsers2->toArray());

}); Route :: get(' / getMessages {id}',function($ id){

$userMsg = DB::table('messages')
    ->where('conversation_id', $id)->get();
// echo $userMsg;
return $userMsg;

}); 路线::交(' /的sendMessage',' MessagesController @的sendMessage&#39);

路线::得到(' NewMessage作为/ {ID}',' MessagesController @ NewMessage作为&#39); Route :: post(' sendNewMessage',' MessagesController @ sendNewMessage');

这些是控制器功能

public function sendMessage(Request $request){

    $conID= $request->conID;
     $msg= $request->msg;


    $checkUserId = DB::table('messages')->where('conversation_id', $conID)->get();
    if($checkUserId[0]->user_from== Auth::user()->id){
        // fetch user_to
        $fetch_userTo = DB::table('messages')->where('conversation_id', $conID)
            ->get();
        $userTo = $fetch_userTo[0]->user_to;
    }else{

        $fetch_userTo = DB::table('messages')->where('conversation_id', $conID)
            ->get();
        $userTo = $fetch_userTo[0]->user_to;
    }

    // now send message
    $sendM = DB::table('messages')->insert([
        'user_to' => $userTo,
        'user_from' => Auth::user()->id,
        'msg' => $msg,
        'status' => 1,
        'conversation_id' => $conID
    ]);
    if($sendM){
        $userMsg = DB::table('messages')
            ->join('users', 'users.id','messages.user_from')
            ->where('messages.conversation_id', $conID)->get();
        return $userMsg;
    }

}
public function newMessage($id){
    $uid = Auth::user()->id;

    $friend = DB::table('users')->where("id", "=", $id)->first();

    return view('newMessage', compact('friend'));




}
public function sendNewMessage(Request $request)
{
    $msg = $request->msg;
    $friend_id = $request->friend_id;

    $myID = Auth::user()->id;

    $checkCon1 = DB::table('conversations')->where('user_one',$myID)
        ->where('user_two',$friend_id)->get(); 
   $checkCon2 = DB::table('conversations')->where('user_two',$myID)
        ->where('user_one',$friend_id)->get();
    $allCons = array_merge($checkCon1->toArray(),$checkCon2->toArray());


    if(count($allCons)!=0){
        $conID = $allCons[0]->id;
        $MsgSent = DB::table('messages')->insert([
            'user_from' => $myID,
            'user_to' => $friend_id,
            'msg' => $msg,
            'conversation_id' =>  $conID,
            'status' => 1
        ]);


    }
    else{

        $con = new Conversation();
        $con->user_one = $myID;
        $con->user_two = $friend_id;


        $con->save();
        echo $con->id;

        $MsgSent = DB::table('messages')->insert([
            'user_from' => $myID,
            'user_to' => $friend_id,
            'msg' => $msg,
            'conversation_id' =>  $con->id,
            'status' => 1
        ]);


    }







}

1 个答案:

答案 0 :(得分:0)

/ **  *首先我们将加载所有这个项目的JavaScript依赖项  *包括Vue和其他图书馆。这是一个很好的起点  *使用Vue和Laravel构建强大,强大的Web应用程序。  * /

要求( './引导');

window.Vue = require('vue');

从'vue'导入Vue 从'vue-chat-scroll'导入VueChatScroll Vue.use(VueChatScroll) //加载组件vuejs Vue.component('example-component',require('./ components / ExampleComponent.vue')); Vue.component('chatbox',require('./ components / Chatbox.vue'));

const app = new Vue({     el:'#app',     数据:{           msg:'从左侧点击用户:',         getUserChat: '',         privateMsgs:[],         singleMsgs:[],         msgFrom:'',         conID:'',         friend_id:'',         见过1:假,         见:假,         newMsgFrom:'',         打字: '',         BlackchaterUrl:'http://localhost:8000',     },     看:{       msgFrom(){           Echo.private( '聊天')           .whisper('打字',{            name:this.msgFrom,            userid:this.getUserChat           });       }     },     准备好了:function()     {         this.created();     },     ()创建     {         axios.get(this.BlackchaterUrl +'/ getMessages')           .then(response => {             console.log(response.data); //显示是否成功             app.privateMsgs = response.data; //我们将数据放入post数组中           })           .catch(function(error){             console.log(error); //显示是否出现错误           });     },     方法:     {         消息(ID)         {            axios.get(this.BlackchaterUrl +'/ getMessages /'+ id)           .then(response => {             console.log(response.data); //显示是否成功             app.singleMsgs = response.data; //我们在post数组中放置数据             app.conID = response.data [0] .conversation_id;             app.getUserChat = response.data [0] .user_from;           })           .catch(function(error){             console.log(error); //显示是否出现错误           });         },

    inputHandler(e)
    {
        if(e.keyCode ===13 && !e.shiftKey)
        {
            e.preventDefault();
            this.sendMsg();
            this.msgFrom = "";
        }
    },
    sendMsgOld()
    {

        this.sendMsg();
        this.msgFrom = "";

    },
    sendMsg()
    {


        if(this.msgFrom.length != 0)
        {

          axios.post(this.BlackchaterUrl + '/SendMessage', {
            conID: this.conID,
            msg : this.msgFrom
          })
          .then(function (response) {
            console.log(response.data);//show if success
            if(response.status===200)
            {
                app.singleMsgs = response.data;
            } 
          })
          .catch(function (error) {
            console.log(error);//show if get some error
          });
        }
    },
    friendID: function(id)
    {
      app.friend_id = id;
    },
    inputHandler1(e)
    {
        if(e.keyCode ===13 && !e.shiftKey)
        {
            e.preventDefault();
            this.sendNewMsg();
            this.msgFrom = "";
        }
    },
     sendNewMsg()
    {
            axios.post(this.BlackchaterUrl + '/sendNewMessage', {
            friend_id: this.friend_id,
            msg: this.newMsgFrom,
          })
          .then(function (response) {
            console.log(response.data); // show if success
            if(response.status===200){
              window.location.replace('http://localhost:8000/messages');
              app.msg = 'your message has been sent successfully';
            }

          })
          .catch(function (error) {
            console.log(error); // run if we have error
          });
   }    
},
mounted()
{
   Echo.private('chat')
     .listen('ChatEvent', (e) => {
        document.getElementById('chatAudioNotif').play();
        this.singleMsgs.push(e);
     //console.log(e);
   })
    .listenForWhisper('typing', (e) => {
      if(e.name !='')
      {
        this.typing = 'typing .........'
      }
      else
      {
        this.typing = ''
      }

   });
}

});