I am learning pusher to use it with Laravel, I am trying to subscribe to private channel using Laravel-echo as follow:
import Echo from 'laravel-echo';
window.Pusher = require('pusher-js');
window.Echo = new Echo({
Pusher.logToConsole = true; //update: added this
broadcaster: 'pusher',
key: process.env.MIX_PUSHER_APP_KEY,
cluster: process.env.MIX_PUSHER_APP_CLUSTER,
encrypted: true
});
var channel = window.Echo.private('roomr');
and per Laravel documentations I have to set authorization in channel.php file so in I wrote in it:
Broadcast::channel('roomr', function ($user) {
logger('hit authorize roomr');
return true;
});
please note that I used logger('hit authorize roomr'); to know if my function is being called, but, when I check the log file it is empty which means that this function is not being called.
using developer tools in google chrome I see there is a post request sent to http://127.0.0.1:8000/broadcasting/auth which return response 200, so, I do not think the authentication is the problem.
Update:
after I added Pusher.logToConsole = true; to my javascript now in chrome console I get:
Pusher : : ["JSON returned from auth endpoint was invalid, yet status
code was 200. Data was: "]
what else I can do? please help me to solve this probem
The problem was in the .env file and I solved it by setting BROADCAST_DRIVER=pusher
Related
I have spend many hours to solve this issue of mine, reading the doc multiple times, googling here and there: SO, Laracast, Larachat, etc, but still couldn't get Laravel Echo to subscribe to Pusher presence channel, and it doesn't show any error in console tab
Public and Private channel are working fine and smooth, users can subscribe, users can listen / trigger event(s)
Note: before creation of this post, I have search questions related to my current issue, none of them have answer
Some questions similar to mine:
https://laravelquestions.com/2020/12/15/laravel-echo-not-joining-presence-channel-in-production/
Laravel Echo + Laravel Passport auth in private / presence websockets channels
https://laravel.io/forum/facing-issues-upon-subscribing-to-presence-channel
etc..
Spec:
Laravel: 7.30.1
laravel-Echo: 1.10.0 (latest; atm)
pusher/pusher-php-server: 4.0
pusher-js: 7.0.3 (latest; atm)
In resource/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,
forceTLS: true,
authEndpoint: '/api/broadcasting/auth',
auth: {
headers: {
'Authorization': `Bearer ${localStorage['token']}`
}
}
});
In routes/api.php
// https://stackoverflow.com/questions/55555844/authorizing-broadcasting-channel-in-an-spa
Route::post('/broadcasting/auth', function (Request $request) {
$pusher = new Pusher\Pusher(
env('PUSHER_APP_KEY'),
env('PUSHER_APP_SECRET'),
env('PUSHER_APP_ID'),
[
'cluster' => env('PUSHER_APP_CLUSTER')
]
);
// This will return JSON response: {auth:"__KEY__"}, see comment below
// https://pusher.com/docs/channels/server_api/authenticating-users
$response = $pusher->socket_auth($request->request->get('channel_name'), $request->request->get('socket_id'));
return $response;
})->middleware('auth:sanctum');
In routes/channels.php
// https://laravel.com/docs/8.x/broadcasting#authorizing-presence-channels
Broadcast::channel('whatever', function ($user) {
return [
'id' => $user->id,
'name' => $user->name
];
});
In home.vue
...
...
created() {
Echo.join('whatever') // DOES NOT WORK, Even in mounted() vue lifehook, and in Pusher dashboard, it doesn't show this channel name
.here((users) => {
console.table(users)
})
}
Q: Why Laravel Echo not subscribing to Pusher presence channel? and even in Pusher, it doesn't show channel name: presence-whatever, only disconnected (after I refreshed the page) and then connected like nothing happen
Thanks in advance
1. Make sure to set the broadcast driver to .env after that do php artisan config:clear
BROADCAST_DRIVER=pusher
2. Ferify your auth.php. I have like this
3. Check your broadcasting.php this is my dev config
4. Check CORS settings I installed fruitcake/laravel-cors and this is my cors.php config
Maybe for you supports_credentials need to be true
5. Check your channels.php. I have
Make sure to set the broadcast driver to env after that do php artisan config:clear
Use window.Echo.channel('whatever') to join the channel.
Had the exact same issue and was stuck for hours.
I changed 'useTLS' to FALSE in config/broadcasting.php and magically got it working.
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.
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
Echo Version: 1.8.0
Laravel Version: 7.0
PHP Version: 7.2.
NPM Version: 6.12.1
Node Version: 12.13.1
Description: I'm trying to send notifications to users,
My pusher connection is good because it sends on public channels
And also, i get this message on my console
[2020-07-24 21:08:09][355] Processed: Illuminate\Notifications\Events\BroadcastNotificationCreated
and on pusher i also see that the message was sent.
I also don't get any errors on my browser console as all the websocket connections are working well.
But i still dont get any messages.
I tried
Echo.private('App.User.' +userId)
.notification((notification) => {
console.log(notification);
});
I also tried
Echo.private('App.User.' + userId)
.listen('.Illuminate\\Notifications\\Events\\BroadcastNotificationCreated', (e) => {
console.log('Event Notification received ', e)
});
Now I turned on Pusher error logging and i got
app.js:42600 Pusher : : ["JSON returned from auth endpoint was invalid, yet status code was 200. Data was: <!DOCTYPE html>\r\n<html lang=\"en\">\r\n
I also followed many tutorials and the docs
All to no avail.
Steps To Reproduce:
Create a notification and declare both the toArray method and toBroadcast methods but echo fails to catch messages from pusher
I finally solved this issue myself
Steps
In my bootstrap.js file
window.Echo = new Echo({
broadcaster: "pusher",
key: "my key",
cluster: "eu",
encrypted: true,
authEndpoint: "api/broadcasting/auth",
auth: {
headers: {
Authorization: "Bearer " + localStorage.getItem("token"),
},
},
});
Then in my routes/api.php file,
Route::middleware('auth:api')->post('broadcasting/auth', function (Request $request) {
$pusher = new Pusher\Pusher(
$app_key,
$app_secret,
$app_id
);
return $pusher->socket_auth($request->request->get('private-my-channel'),($request->request->get('socket_id'));
});
There is more info on this in the documentation,
I hope it helps someone someday
I'm trying to set up a private pusher channel with echo on laravel 6. It won't authorise the user. The best I can do is get the following response from pusher
Pusher : No callbacks on private-App.User.1 for pusher:subscription_error
I've followed the documentation, I've registered:
App\Providers\BroadcastServiceProvider
added the csrf token:
<meta name="csrf-token" content="{{ csrf_token() }}">
adjusted the broadcast routes in the broadcastServiceProvider
Broadcast::routes(["middleware" => ["auth:api"]]);
Required the channels file
require base_path('routes/channels.php');
Here's the channel code, (the log isn't even running)
Broadcast::channel('App.User.{id}', function ($user, $id) {
Log::info('User failed to auth.');
return (int) $user->id === (int) $id;
});
Here's the bootstrap.js code, obviously using my genuine key and endpoint (tried with and without the endpoint)
import Echo from 'laravel-echo'
window.Pusher = require('pusher-js');
window.Echo = new Echo({
broadcaster: 'pusher',
key: 'mykeyhere111',
cluster: 'eu',
authEndpoint: "https://mydomain.test/broadcasting/auth",
forceTLS: true
});
Pusher.logToConsole = true;
console.log(window.Echo.options);
and my vue listen method:
Echo.private(`App.User.${userId}`)
.notification( (notification) => {
console.log(notification)
})
I've also set the env file
BROADCAST_DRIVER=pusher
PUSHER_APP_ID=akeyhere1
PUSHER_APP_KEY=akeyhere123
PUSHER_APP_SECRET=akeyhere12345
PUSHER_APP_CLUSTER=eu
I'm working on homestead with ssl, also tried on vagrant. The network response for auth is:
Request URL: https://mysite.test/broadcasting/auth
Request Method: POST
Status Code: 302
with no response data.
I've spent a couple of days trying to get this working, nothing seems to do it. Any ideas?
Is there any guide about this topic? I have read the pusher documentation and it seems fairly easy to manage a disconnect with a code similar to the following:
pusher.connection.bind('disconnected', function() {
// Do Something
})
I'm not sure how to integrate it with Echo, since my code is as follows:
window.EchoConnection = new Echo({
broadcaster: 'pusher',
key: window.EchoKey,
cluster: 'eu',
encrypted: true
});
EDIT: in order to check a disconnect event, run window.EchoConnection.connector.pusher.connection.disconnect() in your console
I haven't tried it yet, but according to the github repo this should work for pusher:
window.EchoConnection is an Echo Object. When you create a new pusher instance with echo, the connector variable will be a PusherConnector:
if (this.options.broadcaster == 'pusher') {
this.connector = new PusherConnector(this.options);
}
Over this variable you can find the Pusher instance that is created:
connect(): void {
this.pusher = new Pusher(this.options.key, this.options);
}
The theoretical solution for binding events to the pusher would be:
window.EchoConnection.connector.pusher.connection.bind('disconnected', function() {
// Do Something
})