Why broadcasting channel public not working? Larav

2019-09-16 17:38发布

问题:

I use laravel 5.3

I make routes/channels.php like this :

<?php
Broadcast::channel('messages', function() {
    return true;
});

If I input the data cart and click submit, it will run this :

this.$http.post(window.BaseUrl + '/guest/add-notification', {cart_data: JSON.stringify(data)});

It will call function on the controller

The function like this :

public function addNotification(Request $request){
    $input = $request->only('cart_data');
    $data = json_decode($input['cart_data'], true);
    event(new CartNotificationEvent($data));
}

Then it will call event

The event like this :

<?php
namespace App\Events;
use Illuminate\Broadcasting\Channel;
use Illuminate\Queue\SerializesModels;
use Illuminate\Broadcasting\PrivateChannel;
use Illuminate\Broadcasting\PresenceChannel;
use Illuminate\Broadcasting\InteractsWithSockets;
use Illuminate\Contracts\Broadcasting\ShouldBroadcast;
class CartNotificationEvent
{
    use InteractsWithSockets, SerializesModels;
    public $data;
    public function __construct($data)
    {
        $this->data = $data;
    }
    public function broadcastWith()
    {
        return [
            'message' => $this->data,
        ];
    }
    public function broadcastAs()
    {
        return 'newMessage';
    }
    public function broadcastOn()
    {
        return new Channel('messages');
    }
}

On the client, I do like this :

Echo.channel('messages')
.listen('.newMessage', (message) => {
    console.log('test')
    console.log(message);
});

When all the code is executed, I check on the console, the console.log not display

Why is it not working?

If I see the whole code that I make, it seems the process is correct

回答1:

class CartNotificationEvent implements ShouldBroadcast is missing.