Search code examples
javascriptlaravelreal-timepusher

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);
});

Solution

  • I think you need to create a Laravel Event through artisan php artisan make:event addANameHere

    Afterwards, inside the event you need to add a channel to be broadcast on e.g.

    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.

    I hope I helped..