Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Laravel Echo "Echo is not defined"

First of all thanks for reading. Let me explain the problem that I'm facing. So I installed Pusher and Laravel Echo successfully and tried to use it in my dash.blade.php, this is how I imported the app.js file: <script src="{{ asset('js/app')}}"></script>. After that I used this:

<script>
  Echo.channel('channelDemoEvent')
    .listen('eventTrigger', (e) => {
      alert('Its working');
    });
</script>

And when running it I get this error in chrome console: Uncaught ReferenceError: Echo is not defined

I searched on the internet for this error more than 2 hours now, and when I added window. before the Echo I got a different error, that error is this: Uncaught TypeError: Cannot read property 'channel' of undefined I have tried to comment these on the app.js because I read that that could make this error: Vue.component('example-component', require('./components/ExampleComponent.vue')); window.Vue = require('vue');

const app = new Vue({
el: '#app',
});`

After commenting those I get the same error. Thanks for reading & have a nice day.

like image 730
Edward Avatar asked Dec 25 '18 16:12

Edward


1 Answers

Here are the steps

composer

Install pusher if you are using pusher

composer require pusher/pusher-php-server "~4.0"

NPM or Yarn

npm install --save laravel-echo pusher-js

If not using pusher then

npm install --save socket.io-client

Blade

Make sure that your template has csrf token like so

<meta name="csrf-token" content="{{ csrf_token() }}">

.env

In .env you should fill in your pusher information

PUSHER_APP_ID=yourpusherappid
PUSHER_APP_KEY=yourpusherappkey
PUSHER_APP_SECRET=yourpusherappsecret
PUSHER_APP_CLUSTER=yourpusherappcluster

MIX_PUSHER_APP_KEY="${PUSHER_APP_KEY}"
MIX_PUSHER_APP_CLUSTER="${PUSHER_APP_CLUSTER}"

webpack.mix.js

In webpack.mix.js

Make sure you have

const mix = require("laravel-mix");
require("dotenv").config();

bootstrap.js

In resources/js/bootstrap.js

Make sure you have uncommented

/**
 * 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,
    encrypted: true
});

Compile

Don't forget to recompile your js files

NPM run watch 
NPM run dev 
NPM run prod 

Config Cache

Sometimes you may need to clear the cache so that changes take effect run the following command

php artisan config:clear

Thanks for upvote

like image 135
Pascal Avatar answered Oct 12 '22 21:10

Pascal