Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Laravel Echo 500 error (broadcasting/auth)?

have a nice day !

I have a problem: I set up Laravel Echo & Pusher but got this error, have no idea to resolve :(

enter image description here

I checked my app-key, app-cluster but all are correct.

Can someone help me?

app.js

const app = new Vue({
    el: '#app',
    data: {
        messages: []
    },
    methods:{
        addMessage(message){
            this.messages.push(message);
            axios.post('/messages', message).then(response => {
               console.log(response);
            });
        }
    },
    created(){
        axios.get('/messages').then(response => {
            this.messages = response.data;
        });

        Echo.channel('chatroom')
            .listen('MessageEvent', (e) => {
                console.log(e);
            });
    }
})

bootstrap.js

import Echo from 'laravel-echo'

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

window.Echo = new Echo({
    broadcaster: 'pusher',
    key: '************',
    cluster: 'ap1',
    encrypted: false
});

MessageEvent

use Dispatchable, InteractsWithSockets, SerializesModels;
public $message, $user;

public function __construct(Message $message, User $user)
{
    $this->message = $message;
    //query
    $this->user = $user;
}

public function broadcastOn()
{
    return new PresenceChannel('chatroom');
}

channels.php

Broadcast::channel('App.User.{id}', function ($user, $id) {
    return (int) $user->id === (int) $id;
});

Broadcast::channel('chatroom', function ($user, $id) {
    return $user;
});
like image 374
Manh Nguyen Avatar asked Jan 28 '23 18:01

Manh Nguyen


1 Answers

Error 403 or 500 /broadcasting/auth with Laravel version > 5.3 & Pusher, you need change your code in resources/assets/js/bootstrap.js with

window.Echo = new Echo({
    broadcaster: 'pusher',
    key: 'your key',
    cluster: 'your cluster',
    encrypted: true,
    auth: {
        headers: {
            Authorization: 'Bearer ' + YourTokenLogin
        },
    },
});

And in app/Providers/BroadcastServiceProvider.php change by

Broadcast::routes()

with

Broadcast::routes(['middleware' => ['auth:api']]);

or

Broadcast::routes(['middleware' => ['jwt.auth']]); //if you use JWT

it worked for me, and hope it help you.

like image 158
Alex Avatar answered Jan 31 '23 09:01

Alex