[英]listen to messages using pusher in Laravel
I need to get echo message in the log when there is massage has been set to me can I listen to the message that has been sent to me through this code当我设置了按摩时,我需要在日志中获取回声消息 我可以收听通过此代码发送给我的消息吗
<script src="https://js.pusher.com/4.1/pusher.min.js"></script>
<script type="text/javascript">
// Enable pusher logging - don't include this in production
Pusher.logToConsole = false;
var pusher = new Pusher('34b9ea6826c359c41c3f', {
cluster: 'eu',
encrypted: true
});
var channel = pusher.subscribe('Messages');
channel.bind('msgSend{{$id}}msgReceive{{Auth::user()->id}}', function(data) {
$('.adsx').append(data.html);
$("html,body").animate({scrollTop: $('.adsx')[0].scrollHeight}, 0);
});
I think you need to create a Laravel Event through artisan php artisan make:event addANameHere
我认为您需要通过artisan php artisan make:event addANameHere
创建一个Laravel Event php artisan make:event addANameHere
Afterwards, inside the event you need to add a channel to be broadcast on eg 之后,在事件内部,您需要添加一个频道,例如
class addANameHere implements ShouldBroadcast {
use Dispatchable, InteractsWithSockets, SerializesModels;
public $user_id;
/**
* Create a new event instance.
*
* @return void
*/
public function __construct($user_id)
{
$this->user_id = $user_id;
}
/**
* Get the channels the event should broadcast on.
*
* @return \Illuminate\Broadcasting\Channel|array
*/
public function broadcastOn()
{
return ['alert-user-'.$this->user_id];
}
Then, you can receive messages like that: 然后,您会收到这样的消息:
var pusher = new Pusher("34b9ea6826c359c41c3f", {
cluster: 'eu',
encrypted: false,
});
var channel = pusher.subscribe('alert-user-{{ Auth::user()->id }}');
channel.bind('App\\Events\\addANameHere', function(data) {
// Do whatever you want here ...
});
In order to trigger that event (When the message is sent) you call your Event Class like that: 为了触发该事件(发送消息时),您可以这样调用事件类:
\Event::dispatch(new addANameHere($user_id));
And the $user_id
is the user you want to see that message. $user_id
是您要查看该消息的用户。
I hope I helped.. 希望我能帮忙
this method is very good but i want to add a little bit.这个方法很好但是我想补充一点。 i think be careful if you think use this method.如果您认为使用此方法,我认为要小心。 don't print cleartext $user_id variable on blade file.不要在刀片文件上打印明文$user_id变量。 because you could have some problem for code security.因为您可能会遇到代码安全问题。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.