I'm trying to setup broadcast just like laravel documentation. I'm using pusher.
Here is my FriendRequestSent event:
class FriendRequestSent implements ShouldBroadcast
{
use Dispatchable, InteractsWithSockets, SerializesModels;
public $id;
public function __construct($id)
{
$this->id = $id;
}
public function broadcastOn()
{
return new Channel('friend-request.' . $this->id);
}
}
And I call it like this:
event(new FriendRequestSent("5a22f7e72e069a2e64001ed5"));
Here is my channel.php
Broadcast::channel('friend-request.{receiverId}', function ($user, $receiverId) {
return true;
});
and this is my script on the page:
<script>
Echo.private(`friend-request.${receiverId}`)
.listen('FriendRequestSent', (e) => {
console.log(e);
});
</script>
Just like documentation. But I get this error in browser's console:
Uncaught ReferenceError: receiverId is not defined.
Could anyone help?
Related
I tried to listen event emited from broadcast in laravel livewire but nothing happen;
on my bootstrap.js i have:
import Echo from 'laravel-echo';
window.Pusher = require('pusher-js');
window.Echo = new Echo({
broadcaster: 'pusher',
key: 'myKey',
wsHost: window.location.hostname,
wsPort: 6001,
disableStat: true,
forceTLS: false,
});
my event laravel
class TaskFinished implements ShouldBroadcast
{
use Dispatchable, InteractsWithSockets, SerializesModels;
public function __construct()
{
//
}
public function broadcastAs(){
return 'task-finish';
}
public function broadcastOn()
{
return new Channel('TaskTricolor');
}
}
my listener
class SendTaskNotif
{
/**
* Create the event listener.
*
* #return void
*/
public function __construct()
{
//
}
/**
* Handle the event.
*
* #param TaskFinished $event
* #return void
*/
public function handle(TaskFinished $event)
{
}
}
and my livewire component
protected $listeners = ['echo:TaskTricolor,TaskFinished' => 'eventlisten'];
// public function getListeners(){
// return [
// 'echo:TaskTricolor,TaskFinished' => 'eventlisten'
// ];
// }
public function start(){
$this->start = true;
$tricolors = new TricolorController();
$this->tricolor = $tricolors->start();
}
public function stop(){
$this->start = false;
$tricolors = new TricolorController();
$this->tricolor = $tricolors->stop();
}
public function emet(){
event(new TaskFinished());
}
public function eventlisten(){
$vars = "test";
dd($vars);
}
on my listener i put dd('test') and when the emet function is called, the dd value is showed;
So when i test with livewire listener handler, nothing happen, my dd not appear, and no error;
I tried to console log Echo from blade to test if i can handle listener, but it show that Echo is not defined, but when i console.log window, i see Echo inside
On my websocket dashboard i have this:
I don't know if it can help to solve, i use beyondcode/laravel-websockets package as driver
When I first started to use Livewire (version 1.0) we listened the messages using vanilla javascript and then called the Livewire.
document.addEventListener("DOMContentLoaded", function () {
window.Echo.private('TaskTricolor')
.listen('.task-finish', (response) => {
window.Livewire.emit('task-finish', response));
}
});
You can try this. It's not a clean solution as your approach, but I think is easier to debug.
I found the issue; on my event class i should use ShouldBroadCastNow instead ShouldBroadCast
class TaskFinished implements ShouldBroadcastNow
{
use Dispatchable, InteractsWithSockets, SerializesModels;
public function __construct()
{
//
}
public function broadcastAs(){
return 'task-finish';
}
public function broadcastOn()
{
return new Channel('TaskTricolor');
}
}
the ShouldBroadCast put the event in queue, so it's not activated on event called, but ShouldBroadCastNow listen the event immediately, here link i found the explanation
add metadata in your template
<meta name="csrf-token" content="{{ csrf_token() }}">
declare token in your boostrap.js
let token = document.head.querySelector('meta[name="csrf-token"]');
window.Echo = new Echo({
broadcaster: 'push',
.....
...
auth: {
headers: {
Authorization: 'Bearer' + token,
},
},
and call event with
document. addEventListener("DOMContentLoaded", function () {
window.Echo.private('TaskTricolor')
.listen('.task-finish', (response) => {
window.Livewire.emit('task-finish'));
}
});
event is:
public $chat ;
public function __construct($chat)
{
$this->chat = $chat;
}
public function broadcastOn()
{
// return new Channel('recieve-chat');
return new PrivateChannel('recieve-chat' );
}
routes/channels.php is:
Broadcast::channel('recieve-chat', function ($user ) {
return true;
// return $user->id === $reciever_id;
});
in blade file:
<script>
window.addEventListener('DOMContentLoaded' , function () {
Echo.private('recieve-chat')
.listen('ChatBroad', (e) => {
window.livewire.emit('recieve:' + e.chat.bid_id , e.chat);
$(chatScrollDown('.chat'+ e.chat.bid_id ));
});
});
</script>
broadcast Channel work properly. but in PrivateChannel is not working. and in console not showing any error
i use laravel echo and pusher
in App\Providers\BroadcastServiceProvider.php
public function boot()
{
Broadcast::routes();
require base_path('routes/channels.php');
}
must like the code. in Broadcast::routes() we dont need any middleware.
My event broadcast looks as:
class OrderStatusUpdate implements ShouldBroadcast
{
use Dispatchable, InteractsWithSockets, SerializesModels;
public $username;
public $message;
public function broadcastAs()
{
return 'my-event';
}
public function __construct($username)
{
$this->username = $username;
$this->message = "Order status by {$username} was changed";
}
public function broadcastOn()
{
return ['my-event'];
}
}
Call event like:
Route::get('/', function () {
OrderStatusUpdate::dispatch('Nick');
return "Event has been sent!";
});
Client side is:
var pusher = new Pusher('018814b79958ee4f2ad1d', {
cluster: 'eu',
forceTLS: true
});
var channel = pusher.subscribe('my-event');
channel.bind('my-event', function(data) {
alert(JSON.stringify(data));
});
All .env settings are correct!
As you can see I use default Laravel settings and channel name. But message comes with error in Pusher server. But I dont get them on HTML page, with code JS showed upper.
Let me explain from client side:
var channel = pusher.subscribe('order');
channel.bind('OrderStatusUpdate', function(data) {
alert(JSON.stringify(data));
});
order id name of channel
OrderStatusUpdate is event name Event
It mean server should be:
public function broadcastAs()
{
return 'OrderStatusUpdate'; // Event name
}
public function broadcastOn()
{
return ['order'];
}
But I am not sure about this array sintax: return ['order'];, try instead this:
public function broadcastOn()
{
return new Channel("order");
}
Im using events to trigger an event to send emails to the user, but im getting an error when i tried to pass extra data.
Order.php
protected $events = [
'created' => Events\NewOrder::class
];
NewOrder.php
use App\Order;
class NewOrder
{
use Dispatchable, InteractsWithSockets, SerializesModels;
public $order;
public function __construct(Order $order)
{
$this->order = $order;
}
public function broadcastOn()
{
return new PrivateChannel('channel-name');
}
}
the Listener:
public function handle(NewOrder $event)
{
Mail::to(Auth::user()->email)->send( new UserOrder( $event->pedido));
}
UserOrder.php
public function __construct(Order $order)
{
$this->order = $order;
$id_order = $order->id;
$details = DB::table('order_product')
->where('order_id', '=', $id_order)
->get();
$this->$details = $details;
}
public function build()
{
return $this->markdown('emails.userorder')->with('details', $this->details);
}
Markdown mail: userorder
#foreach($details as $detail)
{{ $detail->description }}
#endforeach
gave me this error:
Invalid argument supplied for foreach()
Change
$this->$details = $details;
to
$this->details = $details;
Also be sure that variable is declared above the __construct method, like so
public $details; //or protected $details;
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
class CartNotificationEvent implements ShouldBroadcast is missing.