user2722667
user2722667

Reputation: 8661

Laravel only load echo and pusher for logged in users

I wonder if there is a function to only load echo/pusher for logged in users.

Right now I can ofc check in my blade file if the user is logged in, if so I simply load another js file containing:

Echo.channel('channel')
    .listen('event', (e) => {
        console.log('realtime..');
    });

The reason is that I don't want to take up to many connections to pusher.

Even if I load a private channel that the user don't have access to it still counts as a connection to pusher

Echo.private('channel')
        .listen('event', (e) => {
            console.log('realtime..');
        });

Upvotes: 0

Views: 560

Answers (1)

IndianCoding
IndianCoding

Reputation: 2683

You could wrap Echo with condition. I got 3 options on how to do this:

1) Set var in blade before including script:

<script type="text/javascript">
    var isLoggedIn = true;
</script>

<script type="text/javascript" src="path/app.js" />

In js:

if(isLoggedIn){
    Echo.private('channel')
        .listen('event', (e) => {
            console.log('realtime..');
        });
}

2) Make ajax request to check user is logged in before Echo:

$.get('/user/isLoggedIn', function(data){
    if(data){
        Echo.private('channel')
            .listen('event', (e) => {
                console.log('realtime..');
            });
    }
});

3) Just check dom element, that only logged in user can see.

if($('.some_element_that_only_logged_in_user_can_see').length)
    Echo.private('channel')
        .listen('event', (e) => {
            console.log('realtime..');
        });
});

Examples in jquery, but you could implement it with any framework or vanilla js.

Upvotes: 2

Related Questions