Reputation: 2532
I am using Laravel 5.3 on homestead. Here's the code that I am using for broadcasting an event through pusher and laravel echo, to notify the users of a new message in real time -
class NewMessageReceived implements ShouldBroadcast
{
use InteractsWithSockets, SerializesModels;
public $message;
public $user;
public $sender;
/**
* Create a new event instance.
*
* @return void
*/
public function __construct(Message $message, User $user)
{
$this->message = $message;
$this->user = $user;
$this->sender = \Auth::user();
}
/**
* Get the channels the event should broadcast on.
*
* @return Channel|array
*/
public function broadcastOn()
{
return new PrivateChannel('user.'. $this->user->id);
}
}
Here's the code that calls this event-
try{
$m = $privateChat->messages()->save($m);
if( isset(Auth::user()->guide))
event ( new NewMessageReceived( $m, $m->messageable->tourist->user ));
else
event ( new NewMessageReceived( $m, $m->messageable->guide->user ));
return $m;
}
catch(Exception $e){
return $e;
}
There's an ajax call in vue, which receives the response generated by above code i.e $m .
The problem is if I use the code below instead of the above code, response is recieved at least 5 times faster. I just need to remove the event-firing part to make it run faster (which is not desired, since I want to update user in real time)-
try{
$m = $privateChat->messages()->save($m);
return $m;
}
catch(Exception $e){
return $e;
}
It would be helpful if you could help me spot the reason behind this behaviour and how can I make it all happen in real time, instead of the delay existing now.
Upvotes: 4
Views: 2621
Reputation: 71
You should change ShouldBroadcast
to ShouldBroadcastNow
. That will solve the problem with delay.
Upvotes: 6
Reputation: 4806
Try this:
Move your if logic to event Class
class NewMessageReceived implements ShouldBroadcast
{
use InteractsWithSockets, SerializesModels;
public $message;
public $user;
public $sender;
/**
* Create a new event instance.
*
* @return void
*/
public function __construct(Message $message)
{
$this->message = $message;
$this->user = isset(Auth::user()->guide)) ? $message->messageable->tourist->user : $this->user = $message->messageable->guide->user;
$this->sender = \Auth::user();
}
/**
* Get the channels the event should broadcast on.
*
* @return Channel|array
*/
public function broadcastOn()
{
return new PrivateChannel('user.'. $this->user->id);
}
}
Now your event call.
$m = $privateChat->messages()->save($m);
event(new NewMessageReceived($m));
return $m;
Upvotes: 1