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.
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
For me the problem was in loading Echo Script before initialization,
So i had to make the listener start after the whole page is loaded
window.addEventListener('load', () =>{
Echo.join(`chat`)
.here((users) => {
console.log(users)
})
.joining((user) => {
console.log(user.name);
})
.leaving((user) => {
console.log(user.name);
})
.error((error) => {
console.error(error);
});
})
Here are some things you can check/do that might resolve your issue:
Make sure that you have uncommented these lines in bootstrap.js
bootstrap.js
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
});
Did you run npm run dev, npm run prod or npm run watch after making your changes?
I am not confident with your js importation. asset('js/app') will return http://localhost/js/app. You probably have to add .js at the end to have everything imported properly.
Check that your js/app.js importation is positioned before your <script></script> tag.
I have used Laravel echo in pure JS and that happened because document wasn't loaded.
document.onreadystatechange = function () {
if (document.readyState === 'complete') {
Echo.listen(...);
}
}
Please follow the below sequence of code
first set window variable
second config vue
window.Echo = new Echo({
broadcaster: 'socket.io',
host: 'http://127.0.0.1:6001'
})
Vue.config.productionTip = false
new Vue({
router,
store,
render: h => h(App)
}).$mount('#app')
`
Related
In a new Laravel project created by the installer with the Jetstream option resources/js/app.js has a line that reads:
Vue.mixin({ methods: { route } });
PHPStorm reports that route is an unresolved variable or type. This happens, PHPStorm can be wrong. In a newly created application this does not cause an error.
However, when I upgraded an existing project to Laravel 8.10.0 and installed Jetstream via composer this does cause and issue. When running this npm run dev does not error, but the browser will report app.js:44258 Uncaught ReferenceError: route is not defined.
I can find no difference in app.js or bootstrap.js that would cause this. Where does this get imported or included so that I can check if it was done correctly in my upgrade?
The newly created app and the update both create a Blade template that includes the #routes directive. As I was comparing existing files I did not notice this difference.
This can be corrected by including the #routes directive in your blade template prior to the main scripts being loaded, as documented in the installation guide for ziggy.
With the suggestion of ToothlessRebel, this is how I solved my error :
Step 1 command line :
composer require tightenco/ziggy
npm install ziggy-js
php artisan ziggy:generate "resources/js/ziggy.js"
step 2 : modify webpack.mix.js :
mix.js('resources/js/app.js', 'public/js')
...
.webpackConfig(require('./webpack.config'));
And in ./webpack.config :
const path = require('path');
module.exports = {
resolve: {
alias: {
'#': path.resolve('resources/js'),
ziggy: path.resolve('vendor/tightenco/ziggy/src/js/route.js'),
},
},
};
Step 3 : app.js :
import route from 'ziggy';
import {
Ziggy
} from './ziggy';
...
Vue.mixin({
methods: {
route: (name, params, absolute) => route(name, params, absolute, Ziggy),
},
});
...
new Vue({
el: "#app",
render: (h) =>
h(InertiaApp, {
props: {
initialPage: JSON.parse(app.dataset.page),
resolveComponent: (name) => require(`./Pages/${name}`).default,
},
}),
});
and finally a command : npm run dev
So, my dashboard and all mixin/ziggy routes are working...
Not anymore my vue-router routes ... I guess I have a conflit I have to resolve, but it's an other problem
I have setup a Laravel 8 installation that uses Jetstream (inertia js stack). All Jetstream provided views are working correctly.
The issue is when I create a new Route that renders a new Vue template, I get this error in my console:
app.js:30559 [Vue warn]: Error in created hook: "Error: Cannot find module './Test'"
My Route created in web.php
Route::get('/test', function() {
return Inertia\Inertia::render('Test');
});
The 'Test.vue' file is in the 'resources/js/Pages' directory.
<template>
<h2 class="font-semibold text-xl text-gray-800 leading-tight">
Testing
</h2>
</template>
app.js
require('./bootstrap');
import Vue from 'vue';
import { InertiaApp } from '#inertiajs/inertia-vue';
import { InertiaForm } from 'laravel-jetstream';
import PortalVue from 'portal-vue';
Vue.use(InertiaApp);
Vue.use(InertiaForm);
Vue.use(PortalVue);
const app = document.getElementById('app');
new Vue({
render: (h) =>
h(InertiaApp, {
props: {
initialPage: JSON.parse(app.dataset.page),
resolveComponent: (name) => require(`./Pages/${name}`).default,
},
}),
}).$mount(app);
Any idea why the Test.vue template is not being found?
Maybe somebody else is getting here like I did - I had to open developer console in Chrome and make sure that in the Network tab, I had disable cache checked.
And on top, had to go into my server and do php artisan optimize to clear cached views.
Just needed to run 'npm run dev'
You should run this command: npm run watch
It will tracks all your changes and update the application.
Check if you have npm run watch or imho better npx mix watch. Try to php artisan optimize and of course, "hard reload" your browser - for Chrome it is Control+Shift+Delete on Windows and Command+Shift+Delete on MacOS
You need to run npm watch for the vue pages to render:
Route::middleware(['auth:sanctum', 'verified'])
->get('/chat', function () {
return Inertia::render('Chat/container');
})
->name('chat');
The error for me was in the way i created the module directory, it contained additional invisible characters different from its intended name so i had to recreate the directory and that solved it.
Ps : Anyone trying this can just refactor if possible
I am tryint to create a chat app using vue cli project with laravel-echo. But getting error as 419 unknown status /broadcasting/auth.
This is my main.js filr
import Vue from "vue";
import App from "./App.vue";
import "./registerServiceWorker";
import router from "./router";
import store from "./store";
import i18n from "./i18n";
import VueConfirmDialog from "vue-confirm-dialog";
import VueChatScroll from "vue-chat-scroll";
import Echo from "laravel-echo";
Vue.use(VueConfirmDialog);
Vue.config.productionTip = false;
new Vue({
router,
store,
i18n,
render: h => h(App)
}).$mount("#app");
window.Pusher = require("pusher-js");
window.Echo = new Echo({
broadcaster: "pusher",
// key: process.env.MIX_PUSHER_APP_KEY,
host: "http://localhost:8000",
authEndpoint: "http://localhost:8000/broadcasting/auth",
key: "key",
// cluster: process.env.MIX_PUSHER_APP_CLUSTER,
cluster: "ap2",
forceTLS: true
});
and this is how i am trying to listen to events
window.Echo.channel("Chat").listen("SessionEvent", e => {
let friend = this.friends.find(friend => friend.id === e.session_by);
friend.session = e.session;
this.listenForEverySession(friend);
});
Can anyone tell me whats the problem? This is front end and laravel project is backend
This is error I am getting
in your channels.php add guards
Broadcast::channel('Chat', function ($user) {
return true;
}, ['guards' => 'web']); // add this guards
and remove authEndpoint it should auto detect
I am using Channel broadcasting with laravel and vue.js in order to have all user online and offline.
I have installed the package correctly and configured pusher params according to laravel documentation.
In my vue component I wrote following to see who is online on the related channel:
created() {
this.getFriends();
window.Echo.join('Room')
.here(users => {
});
}
But I get following error:
Error in created hook: "TypeError: window.Echo is undefined"
"
Boostrap.js
import Echo from 'laravel-echo';
window.Pusher = require('pusher-js');
window.Echo = new Echo({
broadcaster: 'pusher',
//key: process.env.MIX_PUSHER_APP_KEY,
key:'****************',
//cluster: process.env.MIX_PUSHER_APP_CLUSTER,
cluster: 'eu',
encrypted: true
});
In Laravel version 6 the follwing error happens with vue in the console:
app.js:24703 Uncaught ReferenceError: require is not defined
at app.js:24703
the error points to:
require('./bootstrap');
Webpack.mix.js:
mix.scripts([
'resources/js/jquery-3.4.1.js',
'resources/js/bootstrap.min.js',
'resources/js/toastr.js',
'resources/js/vue.js',
'resources/js/axios.js',
'resources/js/app.js'
], 'public/js/app.js')
.styles([
'resources/css/bootstrap.min.css',
'resources/css/toastr.css'
], 'public/css/app.css');
It works fine VUEJS for me but it doesn’t allow me to add components
Also another thing that I notice is that this error disables me vue devtools.
The code is newly installed, both the Laravel and Vue project and if I create a new project I get the same error.
require('./bootstrap');
window.Vue = require('vue');
Vue.component('message', require('./components/message.vue').default);
const app = new Vue({
el: '#app',
data:{
message: ''
},
methods:{
send(){
if(this.message.length !=0){
console.log(this.message);
}
}
}
});
What am I doing wrong?
It sounds like, somehow, the file is given to the browser hasn't been compiled.
You need to change the configuration Webpack.mix.js
You can try change mix.scripts([]) on mix.js([]) and add .vue().
It helped me.
mix.js([
'resources/js/jquery-3.4.1.js',
'resources/js/bootstrap.min.js',
'resources/js/toastr.js',
'resources/js/vue.js',
'resources/js/axios.js',
'resources/js/app.js'
], 'public/js/app.js') .vue();