philip Njuguna
philip Njuguna

Reputation: 23

Using Laravel 5.4 pusher

I am having trouble making pusher work . I have followed the documentation but I donot know the problem is.. The console returns null.

public function broadcastOn()
{

    return new PrivateChannel('my-channel');
}

and here is my js for pusher.

 <script src="https://js.pusher.com/4.0/pusher.min.js"></script>
<script>
(function () {



    // Enable pusher logging - don't include this in production
    Pusher.logToConsole = true;

var pusher = new Pusher('6049410e84e42d918b14', { encrypted: true });

    var channel = pusher.subscribe('my-channel');

    channel.bind('\Dms\Events\NewNotification', addMessage);

    function addMessage(data) {
        var listItem = $("<li class='list-group-item'></li>");
        listItem.html(data.message);
        $('#messages').prepend(listItem);

        console.log(data.message)
    }

})()

Above is all the code that I have used as test. Please anyone who have done this assist. Laravel 5.4 is what am using right now. Below is the error code. enter image description here

Upvotes: 2

Views: 787

Answers (1)

jcsoriano
jcsoriano

Reputation: 350

In Laravel 5.4, Private channels have a prefix of private- added to it. So try changing this:

 var channel = pusher.subscribe('my-channel');

to this:

 var channel = pusher.subscribe('private-my-channel');

Secondly, check your string, you will need to escape backslashes. So '\Dms\Events\NewNotification' should be this: '\\Dms\\Events\\NewNotification'

Finally, I would recommend using Laravel Echo as it makes things really easy to work with Pusher and Laravel. With Echo, these two lines of code:

var channel = pusher.subscribe('my-channel');

channel.bind('\Dms\Events\NewNotification', addMessage);

Will look like this:

Echo.private('my-channel')
    .listen('\\Dms\\Events\\NewNotification', addMessage);

Notice you don't have to write the prefix private- anymore.

Upvotes: 1

Related Questions