How to use laravel echo without webpack - laravel

There is a limitation of bandwidth usage of my website.So I want get the Laravel Echo from a cdn server instead of my own server.
I tried in my test.blade.php
<script src="https://cdn.jsdelivr.net/npm/socket.io-client#2.1.0/dist/socket.io.js"></script>
<script src="https://cdn.jsdelivr.net/npm/laravel-echo#1.3.5/dist/echo.min.js"></script>
<script>
import Echo from 'laravel-echo'
window.io = require('socket.io-client');
if (typeof io !== 'undefined') {
window.Echo = new Echo({
broadcaster: 'socket.io',
host: 'http://www.test2.com:6001',
});
}
window.Echo.private(`orderStatus-1`) // 私有频道
.listen('.App\\Events\\OrderShipped', (e) => {
console.log(e);
});
But it's not working.

just include these codes in your app.blade.php
<script src="https://cdn.jsdelivr.net/npm/socket.io-client#2.1.1/dist/socket.io.js"></script>
<script src="https://github.com/glitterlip/echoexample/blob/master/public/js/echocompiled.js"></script>

Related

Laravel Broadcasting toOthers

I try to use toOhers() method in broadcasting. In documentation write for this need socketId and I use this in bootstrap.js
import Echo from 'laravel-echo';
window.Pusher = require('pusher-js');
let socketId = Echo.socketId();
window.Echo = new Echo({
headers: {
'X-Socket-ID' : socketId,
},
broadcaster: 'pusher',
key: process.env.MIX_PUSHER_APP_KEY,
cluster: process.env.MIX_PUSHER_APP_CLUSTER,
forceTLS: false,
});
and blade file
<script src="{{ asset('js/app.js') }}"></script>
<script>
Echo.channel('private-orders-auth')
.listen('OrderStatusUpdateAuth', (e) => {
console.log(e);
});
</script>
But this error come
[1]: https://i.stack.imgur.com/grJ5V.png
TypeError: laravel_echo__WEBPACK_IMPORTED_MODULE_0__.default.socketId is not a function
How I can fix it? Thank for the answers!
In general, where I can find an example code for toOrhers method for broadcasting?

Pusher: Difference between channel binding and Laravel echo

I recently worked on a notification system using Pusher and Laravel. unfortunately can't make it work this way:
import Echo from 'laravel-echo'
window.Pusher = require('pusher-js');
Pusher.logToConsole = true;
window.Echo = new Echo({
broadcaster: 'pusher',
key: 'WORKING KEY ..',
cluster : "mt1",
encrypted: true
});
and
window.Echo.channel('post')
.listen('ArticleEvent', function (e) {
console.log(e);
});
While messages was sent to client console, but Listen didn't worked at all... and nothing logged.
anyway I used this way and it worked:
window.Pusher = require('pusher-js');
var pusher = new Pusher('WORKING KEY ..', {
encrypted: true,
cluster: 'mt1',
});
var channel = pusher.subscribe('post');
channel.bind('ArticleEvent', function(e) {
alert(JSON.stringify(e['message']));
});
What is deference between 2 ways and which must be preferred?
You need to include namespace information in the Listen method.
Please try using (note the . character):
window.Echo.channel('post')
.listen('.ArticleEvent', function (e) {
console.log(e);
});

Socket IO client should be globally available error

I am using nuxt/laravel api with laravel-echo-server and socket.io-client.
When I use it this way:
import Echo from 'laravel-echo'
if (process.client) {
window.io = require('socket.io-client')
window.Echo = new Echo({
broadcaster: 'socket.io',
host: 'http://seekers-backend.com:6001',
auth: { headers: { Authorization: 'Bearer-token' } }
})
}
And then use window.Echo.private().listen().... it works perfectly..
But when I try to declare it within data property I get error because that is rendered on server side... How can I use socket.io-client on server side rendering or how can I declare it on client side since I need access to getters for Bearer token.
I guess I found the way that works for unknown reason :D
import Echo from 'laravel-echo'
if (process.client) {
window.io = require('socket.io-client')
}
And then
mounted() {
let echo = new Echo({
broadcaster: 'socket.io',
host: 'http://seekers-backend.com:6001',
auth: { headers: { Authorization: this.token } }
})
echo.private('user.' + this.$auth.user.id)
.listen('MessageEvent', (e) => {
// Do stuff
})
}

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.
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')
`

Laravel 5.5 bootstrap error

I am getting below error.
Uncaught Error: Bootstrap's JavaScript requires jQuery. jQuery must be
included before Bootstrap's JavaScript.
app.js
require('./bootstrap');
window.Vue = require('vue');
import Vue from 'vue';
import VueRouter from 'vue-router';
Vue.use(VueRouter);
import VueAxios from 'vue-axios';
import axios from 'axios';
Vue.use(VueAxios, axios);
import App from './App.vue';
import Login from './components/Login.vue';
import Register from './components/Register.vue';
import Activity from './components/Activity.vue';
import SelectPersons from './components/SelectPersons.vue';
const routes = [
{
name: 'Login',
path: '/',
component: Login
},
{
name: 'Register',
path: '/register',
component: Register
},
{
name: 'Activity',
path: '/activity',
component: Activity
},
{
name: 'SelectPersons',
path: '/selectpersons',
component: SelectPersons
}
];
const router = new VueRouter({ mode: 'history', routes: routes});
new Vue(Vue.util.extend({ router }, App)).$mount('#app');
bootstrap.js
window._ = require('lodash');
/**
* We'll load jQuery and the Bootstrap jQuery plugin which provides support
* for JavaScript based Bootstrap features such as modals and tabs. This
* code may be modified to fit the specific needs of your application.
*/
try {
window.$ = window.jQuery = require('jquery');
require('bootstrap-sass');
} catch (e) {}
window.Vue = require('vue');
/**
* We'll load the axios HTTP library which allows us to easily issue requests
* to our Laravel back-end. This library automatically handles sending the
* CSRF token as a header based on the value of the "XSRF" token cookie.
*/
window.axios = require('axios');
window.axios.defaults.headers.common['X-Requested-With'] = 'XMLHttpRequest';
/**
* Next we will register the CSRF Token as a common header with Axios so that
* all outgoing HTTP requests automatically have it attached. This is just
* a simple convenience so we don't have to attach every token manually.
*/
let token = document.head.querySelector('meta[name="csrf-token"]');
if (token) {
window.axios.defaults.headers.common['X-CSRF-TOKEN'] = token.content;
} else {
console.error('CSRF token not found: https://laravel.com/docs/csrf#csrf-x-csrf-token');
}
/**
* 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: 'your-pusher-key'
// });
Here is the file that loads every vue component or blade template pages.
<html>
<head>
{{Html::style('/css/bootstrap.css')}}
{{Html::style('/css/style.css')}}
{{Html::script('/js/bootstrap.js')}}
</head>
<body>
<div id="app">
</div>
<script src="{{asset('js/app.js')}}"></script>
</body>
</html>
I am using Laravel with vue. Can anybody help me to solve this issue?
Thanks
Your app.js contains jquery. so do as the error says and load bootstrap after jquery.
<html>
<head>
{{Html::style('/css/bootstrap.css')}}
{{Html::style('/css/style.css')}}
</head>
<body>
<div id="app">
</div>
<script src="{{asset('js/app.js')}}"></script>
{{Html::script('/js/bootstrap.js')}}
</body>
</html>
Bootstrap required jQuery to run some of its features like the dropdown. the error says "Uncaught Error: Bootstrap's JavaScript requires jQuery. jQuery must be included before Bootstrap's JavaScript.". So first, require the jquery library, then next is the bootstrap.min.js or bootstrap.js. Please feel free to comment if you have any problem with this. And one more thing, it is better to place your all JS files before </body>.
Try this
<html>
<head>
{{Html::style('/css/bootstrap.css')}}
{{Html::style('/css/style.css')}}
</head>
<body>
<div id="app">
</div>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
{{Html::script('/js/bootstrap.js')}}
<script src="{{asset('js/app.js')}}"></script>
</body>
</html>

Resources