Search code examples
laravelvue.jsechopusher

Establishing a connection to Pusher only when needed in a Laravel-Vue js application using Echo


I am developing MPA with Vue.js as the frontend and Laravel as the backend. I need real-time features in only one page (one Vue js component). I followed laravel documentation and I have events, broadcasting, Echo and Pusher all in place and working well. My problem is efficiency. I have Pusher.logToConsole set to true and I noticed that when I load any page in my app, it actually starts a Pusher instance and establishes a connection. I want this to happen only in the vue component that uses real-time features.

This is the code related to Pusher/Echo in my bootstrap.js:

import Echo from 'laravel-echo';

const client = require('pusher-js');

 Pusher.logToConsole = true;

 window.Echo = new Echo({
     broadcaster: 'pusher',
     key: 'my key is here',
     cluster: 'eu',
     clinet: client,
 });

This is the code in the Vuejs component with real-time functionality:

   Echo.private('my-channel')
        .listen('.App\\Events\\myEvent', (e) => {

            console.log(e);


        });   

Is there a way to instantiate Pusher and establish a connection only in the Vue component of interest?


Solution

  • The connection to pusher is made when the new Echo instance is created. As laravel by default assigns this to the window, presumably for convenience, it is called each time you load app.js.

    In your situation, as you only need it once, you can move the new Echo{(... to your vue component, call it in the mounted or created method, and assign it to a data variable. import Echo from 'laravel-echo' will need to be available to wherever you call the new instance, so you could just move that to the top of the component's script. You will need to still assign pusher.js to the window, as this is called behind the scenes by laravel echo.