laravel,socketio and redis chat appliaction, can't make the first request after page reload to emit the...












0















i have been trying to solve this problem since long time but i found nothing,
i am trying to build a simple private chat app using




  • Laravel

  • Socketio

  • Redis,




i built the chat but i have a bug that i can't fix yet,
the problem is when i first open the chat or on page reload when i send the first message it shows up to the receiver at the right time but it doesn't show to its owner although it's emitted to both users , then every other message shows up to both users at the right time , and here is the code,
also the errorevent does the same, it's supposed to send the error message to the its owner but it does not send the first message through socketio .



server.js



var app = require('express')();
var http = require('http').createServer(app);
var io = require('socket.io')(http);
var Redis = require('ioredis');
var redis = new Redis();
var rediserror = new Redis();



redis.psubscribe('private-message-channel.*' , function(err , count) {
console.log('error is '+err+' and count is '+count);
});

redis.on('pmessage' , function(pattern ,channel , message) {
console.log('channel is '+channel+' and message is '+message);
message = JSON.parse(message);

io.emit(channel+':'+message.event , message.data);
});

rediserror.psubscribe('private-error-channel.*' , function(err , count) {
console.log('error is '+err+' and count is '+count);

});

rediserror.on('pmessage' , function( pattern ,channel , message) {
console.log("channel is " + channel + " and message is: " + message);

message = JSON.parse(message);
io.emit(channel+':'+message.event , message.data);
});


var redischatchannel = new Redis();

redischatchannel.psubscribe('private-chat-channel.*' , function(err , count){
console.log('error is '+err+' and count is '+count);
});

redischatchannel.on('pmessage' , function(pattern , channel , message) {
console.log("channel is "+channel +" and message is: "+message);
message = JSON.parse(message);


io.emit(channel+':'+message.event , message.data);

});

http.listen(3000, function () {
console.log('server lisening at port 3000');
});


chatroom.blade.php



@extends('layouts.app')

@section('content')

@if(!$messages)

<h3>No Messages in your chat with {{$to->name}} yet</h3>
@else
<div id="msgs">
@foreach($messages as $message)
<p><em><b>{{$message->fromusername}}</b></em> : {{$message->body}}</p>
<hr>
@endforeach
</div>
@endif

<form id="chatform" >
<div class="form-group">
<input type="text" id="body"/>
</div>

<div class="form-group">
<input type="submit" class="btn btn-primary" value="Send" />
</div>
</form>


@endsection

@section('script')
<script>

var socket = io('http://localhost:3000');


socket.removeAllListeners(`private-chat-channel.{{$chatid}}.{{auth()->user()->id}}:App\Events\ChatEvent`);
socket.on(`private-chat-channel.{{$chatid}}.{{auth()->user()->id}}:App\Events\ChatEvent` , function(msg){
//console.log(msg);
$('#msgs').append(`<p><em><b>${msg.data.fromusername}</b></em> : ${msg.data.body}</p><hr>`)
});

$('#chatform').submit(function(e) {
e.preventDefault();
var body = $('#body').val();
var chatid ={{$chatid}} ;
axios.post('/store-message' , {
body:body,
chatid:chatid
}).then( function(response){
console.log(response);
var message=response;
socket.removeAllListeners(`private-message-channel.${message.data.from}.${message.data.to}:App\Events\MessageEvent`);
socket.on(`private-message-channel.${message.data.from}.${message.data.to}:App\Events\MessageEvent` , function(msg) {
console.log(msg);
$('#msgs').append(`<p><em><b>${msg.data.fromusername}</b></em> : ${msg.data.body}</p><hr>`);
$('#body').val('');
});
}).catch(function(error){
socket.removeAllListeners(`private-error-channel.{{auth()->user()->id}}:App\Events\ErrorMessage`);
socket.on(`private-error-channel.{{auth()->user()->id}}:App\Events\ErrorMessage` , function(msg){
console.log(msg);
});
console.error(error);
});
})

</script>
@endsection


store_message method from chat controller



public function store_message(Request $request)
{
$validator = Validator::make($request->all() , [
'chatid' => 'required',
'body' => 'required'
]);

if($validator->fails())
{
event(new ErrorMessage( auth()->user() ,$validator->errors()));

return response()->json(['errors' => $validator->errors()] , 400);
}
//dd($request);
if(!Chat::find($request->input('chatid')))
{
event(new ErrorMessage( auth()->user() ,'chat not found'));
return response()->json(['error'=>'error chat not found'] , 400);
}

$chat = Chat::find($request->chatid);

if($chat['user1_id'] == auth()->user()->id)
{
$to = $chat['user2_id'];
} elseif($chat['user2_id'] == auth()->user()->id)
{
$to = $chat['user1_id'];
}
//dd($to);
$message = new Message;
$message->chat_id = $request->chatid;
$message->from = auth()->user()->id;
$message->to = $to;
$message->fromusername= auth()->user()->name;
$message->tousername = User::find($to)->name;
$message->body = $request->body;
$message->save();
event(new MessageEvent(auth()->user() , $message));
event(new ChatEvent($request->chatid , $to ,$message));
return $message;
}


MessageEvent.php



<?php

namespace AppEvents;

use IlluminateBroadcastingChannel;
use IlluminateQueueSerializesModels;
use IlluminateBroadcastingPrivateChannel;
use IlluminateBroadcastingPresenceChannel;
use IlluminateFoundationEventsDispatchable;
use IlluminateBroadcastingInteractsWithSockets;
use IlluminateContractsBroadcastingShouldBroadcast;
use AppUser;

class MessageEvent implements ShouldBroadcast
{
use Dispatchable, InteractsWithSockets, SerializesModels;

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

/**
* Get the channels the event should broadcast on.
*
* @return IlluminateBroadcastingChannel|array
*/
public function broadcastOn()
{
return new PrivateChannel('message-channel.'.$this->user->id.'.'.$this->data->to);
}
}


ErrorEvent.php



<?php

namespace AppEvents;

use IlluminateBroadcastingChannel;
use IlluminateQueueSerializesModels;
use IlluminateBroadcastingPrivateChannel;
use IlluminateBroadcastingPresenceChannel;
use IlluminateFoundationEventsDispatchable;
use IlluminateBroadcastingInteractsWithSockets;
use IlluminateContractsBroadcastingShouldBroadcast;
use AppUser;

class ErrorMessage implements ShouldBroadcast
{
use Dispatchable, InteractsWithSockets, SerializesModels;

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

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









share|improve this question



























    0















    i have been trying to solve this problem since long time but i found nothing,
    i am trying to build a simple private chat app using




    • Laravel

    • Socketio

    • Redis,




    i built the chat but i have a bug that i can't fix yet,
    the problem is when i first open the chat or on page reload when i send the first message it shows up to the receiver at the right time but it doesn't show to its owner although it's emitted to both users , then every other message shows up to both users at the right time , and here is the code,
    also the errorevent does the same, it's supposed to send the error message to the its owner but it does not send the first message through socketio .



    server.js



    var app = require('express')();
    var http = require('http').createServer(app);
    var io = require('socket.io')(http);
    var Redis = require('ioredis');
    var redis = new Redis();
    var rediserror = new Redis();



    redis.psubscribe('private-message-channel.*' , function(err , count) {
    console.log('error is '+err+' and count is '+count);
    });

    redis.on('pmessage' , function(pattern ,channel , message) {
    console.log('channel is '+channel+' and message is '+message);
    message = JSON.parse(message);

    io.emit(channel+':'+message.event , message.data);
    });

    rediserror.psubscribe('private-error-channel.*' , function(err , count) {
    console.log('error is '+err+' and count is '+count);

    });

    rediserror.on('pmessage' , function( pattern ,channel , message) {
    console.log("channel is " + channel + " and message is: " + message);

    message = JSON.parse(message);
    io.emit(channel+':'+message.event , message.data);
    });


    var redischatchannel = new Redis();

    redischatchannel.psubscribe('private-chat-channel.*' , function(err , count){
    console.log('error is '+err+' and count is '+count);
    });

    redischatchannel.on('pmessage' , function(pattern , channel , message) {
    console.log("channel is "+channel +" and message is: "+message);
    message = JSON.parse(message);


    io.emit(channel+':'+message.event , message.data);

    });

    http.listen(3000, function () {
    console.log('server lisening at port 3000');
    });


    chatroom.blade.php



    @extends('layouts.app')

    @section('content')

    @if(!$messages)

    <h3>No Messages in your chat with {{$to->name}} yet</h3>
    @else
    <div id="msgs">
    @foreach($messages as $message)
    <p><em><b>{{$message->fromusername}}</b></em> : {{$message->body}}</p>
    <hr>
    @endforeach
    </div>
    @endif

    <form id="chatform" >
    <div class="form-group">
    <input type="text" id="body"/>
    </div>

    <div class="form-group">
    <input type="submit" class="btn btn-primary" value="Send" />
    </div>
    </form>


    @endsection

    @section('script')
    <script>

    var socket = io('http://localhost:3000');


    socket.removeAllListeners(`private-chat-channel.{{$chatid}}.{{auth()->user()->id}}:App\Events\ChatEvent`);
    socket.on(`private-chat-channel.{{$chatid}}.{{auth()->user()->id}}:App\Events\ChatEvent` , function(msg){
    //console.log(msg);
    $('#msgs').append(`<p><em><b>${msg.data.fromusername}</b></em> : ${msg.data.body}</p><hr>`)
    });

    $('#chatform').submit(function(e) {
    e.preventDefault();
    var body = $('#body').val();
    var chatid ={{$chatid}} ;
    axios.post('/store-message' , {
    body:body,
    chatid:chatid
    }).then( function(response){
    console.log(response);
    var message=response;
    socket.removeAllListeners(`private-message-channel.${message.data.from}.${message.data.to}:App\Events\MessageEvent`);
    socket.on(`private-message-channel.${message.data.from}.${message.data.to}:App\Events\MessageEvent` , function(msg) {
    console.log(msg);
    $('#msgs').append(`<p><em><b>${msg.data.fromusername}</b></em> : ${msg.data.body}</p><hr>`);
    $('#body').val('');
    });
    }).catch(function(error){
    socket.removeAllListeners(`private-error-channel.{{auth()->user()->id}}:App\Events\ErrorMessage`);
    socket.on(`private-error-channel.{{auth()->user()->id}}:App\Events\ErrorMessage` , function(msg){
    console.log(msg);
    });
    console.error(error);
    });
    })

    </script>
    @endsection


    store_message method from chat controller



    public function store_message(Request $request)
    {
    $validator = Validator::make($request->all() , [
    'chatid' => 'required',
    'body' => 'required'
    ]);

    if($validator->fails())
    {
    event(new ErrorMessage( auth()->user() ,$validator->errors()));

    return response()->json(['errors' => $validator->errors()] , 400);
    }
    //dd($request);
    if(!Chat::find($request->input('chatid')))
    {
    event(new ErrorMessage( auth()->user() ,'chat not found'));
    return response()->json(['error'=>'error chat not found'] , 400);
    }

    $chat = Chat::find($request->chatid);

    if($chat['user1_id'] == auth()->user()->id)
    {
    $to = $chat['user2_id'];
    } elseif($chat['user2_id'] == auth()->user()->id)
    {
    $to = $chat['user1_id'];
    }
    //dd($to);
    $message = new Message;
    $message->chat_id = $request->chatid;
    $message->from = auth()->user()->id;
    $message->to = $to;
    $message->fromusername= auth()->user()->name;
    $message->tousername = User::find($to)->name;
    $message->body = $request->body;
    $message->save();
    event(new MessageEvent(auth()->user() , $message));
    event(new ChatEvent($request->chatid , $to ,$message));
    return $message;
    }


    MessageEvent.php



    <?php

    namespace AppEvents;

    use IlluminateBroadcastingChannel;
    use IlluminateQueueSerializesModels;
    use IlluminateBroadcastingPrivateChannel;
    use IlluminateBroadcastingPresenceChannel;
    use IlluminateFoundationEventsDispatchable;
    use IlluminateBroadcastingInteractsWithSockets;
    use IlluminateContractsBroadcastingShouldBroadcast;
    use AppUser;

    class MessageEvent implements ShouldBroadcast
    {
    use Dispatchable, InteractsWithSockets, SerializesModels;

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

    /**
    * Get the channels the event should broadcast on.
    *
    * @return IlluminateBroadcastingChannel|array
    */
    public function broadcastOn()
    {
    return new PrivateChannel('message-channel.'.$this->user->id.'.'.$this->data->to);
    }
    }


    ErrorEvent.php



    <?php

    namespace AppEvents;

    use IlluminateBroadcastingChannel;
    use IlluminateQueueSerializesModels;
    use IlluminateBroadcastingPrivateChannel;
    use IlluminateBroadcastingPresenceChannel;
    use IlluminateFoundationEventsDispatchable;
    use IlluminateBroadcastingInteractsWithSockets;
    use IlluminateContractsBroadcastingShouldBroadcast;
    use AppUser;

    class ErrorMessage implements ShouldBroadcast
    {
    use Dispatchable, InteractsWithSockets, SerializesModels;

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

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









    share|improve this question

























      0












      0








      0








      i have been trying to solve this problem since long time but i found nothing,
      i am trying to build a simple private chat app using




      • Laravel

      • Socketio

      • Redis,




      i built the chat but i have a bug that i can't fix yet,
      the problem is when i first open the chat or on page reload when i send the first message it shows up to the receiver at the right time but it doesn't show to its owner although it's emitted to both users , then every other message shows up to both users at the right time , and here is the code,
      also the errorevent does the same, it's supposed to send the error message to the its owner but it does not send the first message through socketio .



      server.js



      var app = require('express')();
      var http = require('http').createServer(app);
      var io = require('socket.io')(http);
      var Redis = require('ioredis');
      var redis = new Redis();
      var rediserror = new Redis();



      redis.psubscribe('private-message-channel.*' , function(err , count) {
      console.log('error is '+err+' and count is '+count);
      });

      redis.on('pmessage' , function(pattern ,channel , message) {
      console.log('channel is '+channel+' and message is '+message);
      message = JSON.parse(message);

      io.emit(channel+':'+message.event , message.data);
      });

      rediserror.psubscribe('private-error-channel.*' , function(err , count) {
      console.log('error is '+err+' and count is '+count);

      });

      rediserror.on('pmessage' , function( pattern ,channel , message) {
      console.log("channel is " + channel + " and message is: " + message);

      message = JSON.parse(message);
      io.emit(channel+':'+message.event , message.data);
      });


      var redischatchannel = new Redis();

      redischatchannel.psubscribe('private-chat-channel.*' , function(err , count){
      console.log('error is '+err+' and count is '+count);
      });

      redischatchannel.on('pmessage' , function(pattern , channel , message) {
      console.log("channel is "+channel +" and message is: "+message);
      message = JSON.parse(message);


      io.emit(channel+':'+message.event , message.data);

      });

      http.listen(3000, function () {
      console.log('server lisening at port 3000');
      });


      chatroom.blade.php



      @extends('layouts.app')

      @section('content')

      @if(!$messages)

      <h3>No Messages in your chat with {{$to->name}} yet</h3>
      @else
      <div id="msgs">
      @foreach($messages as $message)
      <p><em><b>{{$message->fromusername}}</b></em> : {{$message->body}}</p>
      <hr>
      @endforeach
      </div>
      @endif

      <form id="chatform" >
      <div class="form-group">
      <input type="text" id="body"/>
      </div>

      <div class="form-group">
      <input type="submit" class="btn btn-primary" value="Send" />
      </div>
      </form>


      @endsection

      @section('script')
      <script>

      var socket = io('http://localhost:3000');


      socket.removeAllListeners(`private-chat-channel.{{$chatid}}.{{auth()->user()->id}}:App\Events\ChatEvent`);
      socket.on(`private-chat-channel.{{$chatid}}.{{auth()->user()->id}}:App\Events\ChatEvent` , function(msg){
      //console.log(msg);
      $('#msgs').append(`<p><em><b>${msg.data.fromusername}</b></em> : ${msg.data.body}</p><hr>`)
      });

      $('#chatform').submit(function(e) {
      e.preventDefault();
      var body = $('#body').val();
      var chatid ={{$chatid}} ;
      axios.post('/store-message' , {
      body:body,
      chatid:chatid
      }).then( function(response){
      console.log(response);
      var message=response;
      socket.removeAllListeners(`private-message-channel.${message.data.from}.${message.data.to}:App\Events\MessageEvent`);
      socket.on(`private-message-channel.${message.data.from}.${message.data.to}:App\Events\MessageEvent` , function(msg) {
      console.log(msg);
      $('#msgs').append(`<p><em><b>${msg.data.fromusername}</b></em> : ${msg.data.body}</p><hr>`);
      $('#body').val('');
      });
      }).catch(function(error){
      socket.removeAllListeners(`private-error-channel.{{auth()->user()->id}}:App\Events\ErrorMessage`);
      socket.on(`private-error-channel.{{auth()->user()->id}}:App\Events\ErrorMessage` , function(msg){
      console.log(msg);
      });
      console.error(error);
      });
      })

      </script>
      @endsection


      store_message method from chat controller



      public function store_message(Request $request)
      {
      $validator = Validator::make($request->all() , [
      'chatid' => 'required',
      'body' => 'required'
      ]);

      if($validator->fails())
      {
      event(new ErrorMessage( auth()->user() ,$validator->errors()));

      return response()->json(['errors' => $validator->errors()] , 400);
      }
      //dd($request);
      if(!Chat::find($request->input('chatid')))
      {
      event(new ErrorMessage( auth()->user() ,'chat not found'));
      return response()->json(['error'=>'error chat not found'] , 400);
      }

      $chat = Chat::find($request->chatid);

      if($chat['user1_id'] == auth()->user()->id)
      {
      $to = $chat['user2_id'];
      } elseif($chat['user2_id'] == auth()->user()->id)
      {
      $to = $chat['user1_id'];
      }
      //dd($to);
      $message = new Message;
      $message->chat_id = $request->chatid;
      $message->from = auth()->user()->id;
      $message->to = $to;
      $message->fromusername= auth()->user()->name;
      $message->tousername = User::find($to)->name;
      $message->body = $request->body;
      $message->save();
      event(new MessageEvent(auth()->user() , $message));
      event(new ChatEvent($request->chatid , $to ,$message));
      return $message;
      }


      MessageEvent.php



      <?php

      namespace AppEvents;

      use IlluminateBroadcastingChannel;
      use IlluminateQueueSerializesModels;
      use IlluminateBroadcastingPrivateChannel;
      use IlluminateBroadcastingPresenceChannel;
      use IlluminateFoundationEventsDispatchable;
      use IlluminateBroadcastingInteractsWithSockets;
      use IlluminateContractsBroadcastingShouldBroadcast;
      use AppUser;

      class MessageEvent implements ShouldBroadcast
      {
      use Dispatchable, InteractsWithSockets, SerializesModels;

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

      /**
      * Get the channels the event should broadcast on.
      *
      * @return IlluminateBroadcastingChannel|array
      */
      public function broadcastOn()
      {
      return new PrivateChannel('message-channel.'.$this->user->id.'.'.$this->data->to);
      }
      }


      ErrorEvent.php



      <?php

      namespace AppEvents;

      use IlluminateBroadcastingChannel;
      use IlluminateQueueSerializesModels;
      use IlluminateBroadcastingPrivateChannel;
      use IlluminateBroadcastingPresenceChannel;
      use IlluminateFoundationEventsDispatchable;
      use IlluminateBroadcastingInteractsWithSockets;
      use IlluminateContractsBroadcastingShouldBroadcast;
      use AppUser;

      class ErrorMessage implements ShouldBroadcast
      {
      use Dispatchable, InteractsWithSockets, SerializesModels;

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

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









      share|improve this question














      i have been trying to solve this problem since long time but i found nothing,
      i am trying to build a simple private chat app using




      • Laravel

      • Socketio

      • Redis,




      i built the chat but i have a bug that i can't fix yet,
      the problem is when i first open the chat or on page reload when i send the first message it shows up to the receiver at the right time but it doesn't show to its owner although it's emitted to both users , then every other message shows up to both users at the right time , and here is the code,
      also the errorevent does the same, it's supposed to send the error message to the its owner but it does not send the first message through socketio .



      server.js



      var app = require('express')();
      var http = require('http').createServer(app);
      var io = require('socket.io')(http);
      var Redis = require('ioredis');
      var redis = new Redis();
      var rediserror = new Redis();



      redis.psubscribe('private-message-channel.*' , function(err , count) {
      console.log('error is '+err+' and count is '+count);
      });

      redis.on('pmessage' , function(pattern ,channel , message) {
      console.log('channel is '+channel+' and message is '+message);
      message = JSON.parse(message);

      io.emit(channel+':'+message.event , message.data);
      });

      rediserror.psubscribe('private-error-channel.*' , function(err , count) {
      console.log('error is '+err+' and count is '+count);

      });

      rediserror.on('pmessage' , function( pattern ,channel , message) {
      console.log("channel is " + channel + " and message is: " + message);

      message = JSON.parse(message);
      io.emit(channel+':'+message.event , message.data);
      });


      var redischatchannel = new Redis();

      redischatchannel.psubscribe('private-chat-channel.*' , function(err , count){
      console.log('error is '+err+' and count is '+count);
      });

      redischatchannel.on('pmessage' , function(pattern , channel , message) {
      console.log("channel is "+channel +" and message is: "+message);
      message = JSON.parse(message);


      io.emit(channel+':'+message.event , message.data);

      });

      http.listen(3000, function () {
      console.log('server lisening at port 3000');
      });


      chatroom.blade.php



      @extends('layouts.app')

      @section('content')

      @if(!$messages)

      <h3>No Messages in your chat with {{$to->name}} yet</h3>
      @else
      <div id="msgs">
      @foreach($messages as $message)
      <p><em><b>{{$message->fromusername}}</b></em> : {{$message->body}}</p>
      <hr>
      @endforeach
      </div>
      @endif

      <form id="chatform" >
      <div class="form-group">
      <input type="text" id="body"/>
      </div>

      <div class="form-group">
      <input type="submit" class="btn btn-primary" value="Send" />
      </div>
      </form>


      @endsection

      @section('script')
      <script>

      var socket = io('http://localhost:3000');


      socket.removeAllListeners(`private-chat-channel.{{$chatid}}.{{auth()->user()->id}}:App\Events\ChatEvent`);
      socket.on(`private-chat-channel.{{$chatid}}.{{auth()->user()->id}}:App\Events\ChatEvent` , function(msg){
      //console.log(msg);
      $('#msgs').append(`<p><em><b>${msg.data.fromusername}</b></em> : ${msg.data.body}</p><hr>`)
      });

      $('#chatform').submit(function(e) {
      e.preventDefault();
      var body = $('#body').val();
      var chatid ={{$chatid}} ;
      axios.post('/store-message' , {
      body:body,
      chatid:chatid
      }).then( function(response){
      console.log(response);
      var message=response;
      socket.removeAllListeners(`private-message-channel.${message.data.from}.${message.data.to}:App\Events\MessageEvent`);
      socket.on(`private-message-channel.${message.data.from}.${message.data.to}:App\Events\MessageEvent` , function(msg) {
      console.log(msg);
      $('#msgs').append(`<p><em><b>${msg.data.fromusername}</b></em> : ${msg.data.body}</p><hr>`);
      $('#body').val('');
      });
      }).catch(function(error){
      socket.removeAllListeners(`private-error-channel.{{auth()->user()->id}}:App\Events\ErrorMessage`);
      socket.on(`private-error-channel.{{auth()->user()->id}}:App\Events\ErrorMessage` , function(msg){
      console.log(msg);
      });
      console.error(error);
      });
      })

      </script>
      @endsection


      store_message method from chat controller



      public function store_message(Request $request)
      {
      $validator = Validator::make($request->all() , [
      'chatid' => 'required',
      'body' => 'required'
      ]);

      if($validator->fails())
      {
      event(new ErrorMessage( auth()->user() ,$validator->errors()));

      return response()->json(['errors' => $validator->errors()] , 400);
      }
      //dd($request);
      if(!Chat::find($request->input('chatid')))
      {
      event(new ErrorMessage( auth()->user() ,'chat not found'));
      return response()->json(['error'=>'error chat not found'] , 400);
      }

      $chat = Chat::find($request->chatid);

      if($chat['user1_id'] == auth()->user()->id)
      {
      $to = $chat['user2_id'];
      } elseif($chat['user2_id'] == auth()->user()->id)
      {
      $to = $chat['user1_id'];
      }
      //dd($to);
      $message = new Message;
      $message->chat_id = $request->chatid;
      $message->from = auth()->user()->id;
      $message->to = $to;
      $message->fromusername= auth()->user()->name;
      $message->tousername = User::find($to)->name;
      $message->body = $request->body;
      $message->save();
      event(new MessageEvent(auth()->user() , $message));
      event(new ChatEvent($request->chatid , $to ,$message));
      return $message;
      }


      MessageEvent.php



      <?php

      namespace AppEvents;

      use IlluminateBroadcastingChannel;
      use IlluminateQueueSerializesModels;
      use IlluminateBroadcastingPrivateChannel;
      use IlluminateBroadcastingPresenceChannel;
      use IlluminateFoundationEventsDispatchable;
      use IlluminateBroadcastingInteractsWithSockets;
      use IlluminateContractsBroadcastingShouldBroadcast;
      use AppUser;

      class MessageEvent implements ShouldBroadcast
      {
      use Dispatchable, InteractsWithSockets, SerializesModels;

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

      /**
      * Get the channels the event should broadcast on.
      *
      * @return IlluminateBroadcastingChannel|array
      */
      public function broadcastOn()
      {
      return new PrivateChannel('message-channel.'.$this->user->id.'.'.$this->data->to);
      }
      }


      ErrorEvent.php



      <?php

      namespace AppEvents;

      use IlluminateBroadcastingChannel;
      use IlluminateQueueSerializesModels;
      use IlluminateBroadcastingPrivateChannel;
      use IlluminateBroadcastingPresenceChannel;
      use IlluminateFoundationEventsDispatchable;
      use IlluminateBroadcastingInteractsWithSockets;
      use IlluminateContractsBroadcastingShouldBroadcast;
      use AppUser;

      class ErrorMessage implements ShouldBroadcast
      {
      use Dispatchable, InteractsWithSockets, SerializesModels;

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

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






      php laravel-5 redis socket.io






      share|improve this question













      share|improve this question











      share|improve this question




      share|improve this question










      asked Nov 13 '18 at 13:38









      moody9moody9

      12




      12
























          0






          active

          oldest

          votes











          Your Answer






          StackExchange.ifUsing("editor", function () {
          StackExchange.using("externalEditor", function () {
          StackExchange.using("snippets", function () {
          StackExchange.snippets.init();
          });
          });
          }, "code-snippets");

          StackExchange.ready(function() {
          var channelOptions = {
          tags: "".split(" "),
          id: "1"
          };
          initTagRenderer("".split(" "), "".split(" "), channelOptions);

          StackExchange.using("externalEditor", function() {
          // Have to fire editor after snippets, if snippets enabled
          if (StackExchange.settings.snippets.snippetsEnabled) {
          StackExchange.using("snippets", function() {
          createEditor();
          });
          }
          else {
          createEditor();
          }
          });

          function createEditor() {
          StackExchange.prepareEditor({
          heartbeatType: 'answer',
          autoActivateHeartbeat: false,
          convertImagesToLinks: true,
          noModals: true,
          showLowRepImageUploadWarning: true,
          reputationToPostImages: 10,
          bindNavPrevention: true,
          postfix: "",
          imageUploader: {
          brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
          contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
          allowUrls: true
          },
          onDemand: true,
          discardSelector: ".discard-answer"
          ,immediatelyShowMarkdownHelp:true
          });


          }
          });














          draft saved

          draft discarded


















          StackExchange.ready(
          function () {
          StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53282288%2flaravel-socketio-and-redis-chat-appliaction-cant-make-the-first-request-after%23new-answer', 'question_page');
          }
          );

          Post as a guest















          Required, but never shown

























          0






          active

          oldest

          votes








          0






          active

          oldest

          votes









          active

          oldest

          votes






          active

          oldest

          votes
















          draft saved

          draft discarded




















































          Thanks for contributing an answer to Stack Overflow!


          • Please be sure to answer the question. Provide details and share your research!

          But avoid



          • Asking for help, clarification, or responding to other answers.

          • Making statements based on opinion; back them up with references or personal experience.


          To learn more, see our tips on writing great answers.




          draft saved


          draft discarded














          StackExchange.ready(
          function () {
          StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53282288%2flaravel-socketio-and-redis-chat-appliaction-cant-make-the-first-request-after%23new-answer', 'question_page');
          }
          );

          Post as a guest















          Required, but never shown





















































          Required, but never shown














          Required, but never shown












          Required, but never shown







          Required, but never shown

































          Required, but never shown














          Required, but never shown












          Required, but never shown







          Required, but never shown







          Popular posts from this blog

          Xamarin.iOS Cant Deploy on Iphone

          Glorious Revolution

          Dulmage-Mendelsohn matrix decomposition in Python