Use Laravel echo with Laravel mix

2.2k views Asked by At

I am new to the Laravel Mix frontend framework All I want to know is how can we use Laravel Echo with Laravel Mix. I am using Laravel database notifications and I want to show them in real-time to the user.

Notifications are working fine and I am also able to list it to the users. For showing them in real-time I am using Pusher and it integrated well. I have tested by sending some events through debug console. In my project I am unable to find bootstrap.js file to place below code:

let token = document.head.querySelector('meta[name="csrf-token"]'); 
import Echo from "laravel-echo"
window.pusher = require('pusher-js');
window.Echo = new Echo({
    broadcaster: 'pusher',
    key: process.env.MIX_PUSHER_APP_KEY,
    cluster: process.MIX_PUSHER_APP_CLUSTER,
    encrypted: true
});

In app.js file I want to place below code to listen notification real time:

let userId = document.head.querySelector('meta[name="user-id"]').content();
    Echo.private('App.User.'+userId)
    .notification((notification) => {
        console.log(notification.data);
    });

I am using Laravel 7.30.0 version. In my project, I don't have an assets folder. The structure is like below:

resources
        -> Js
           -> app.js

In app.js I have tried to write above code but it throws me below error:

Uncaught SyntaxError: Cannot use import statement outside a module

How can I use Laravel Echo with Laravel Mix? I have no prior experience in Laravel Mix.

1

There are 1 answers

1
Karl Hill On

First, install Laravel Echo and Pusher.

npm install --save-dev laravel-echo pusher-js

In a fresh install of Laravel 7.x there are two files in /resources/js/.

Those are: app.js and bootstrap.js. In bootstrap.js you will see a commented out section for Echo.

/**
 * Echo exposes an expressive API for subscribing to channels and listening
 * for events that are broadcast by Laravel. Echo and event broadcasting
 * allows your team to easily build robust real-time web applications.
 */

// import Echo from 'laravel-echo';

// window.Pusher = require('pusher-js');

// window.Echo = new Echo({
//     broadcaster: 'pusher',
//     key: process.env.MIX_PUSHER_APP_KEY,
//     cluster: process.env.MIX_PUSHER_APP_CLUSTER,
//     forceTLS: true
// });

Remove the comments and go ahead and run npm run dev.

import Echo from 'laravel-echo';

window.Pusher = require('pusher-js');

window.Echo = new Echo({
    broadcaster: 'pusher',
    key: process.env.MIX_PUSHER_APP_KEY,
    cluster: process.env.MIX_PUSHER_APP_CLUSTER,
    encrypted: true
);

Make sure you have the latest version of Mix and that your webpack.mix.js is properly configured.

npm i laravel-mix@latest --save-dev