I am using Laravel Echo in my project to broadcast events to the client-side. Everything is working correctly, however, I am having a problem in eager-loading
the relationships of the model for the Event.
My Controller
$chat = new Chat;
$chat->user_id = $request->user_id;
$chat->message = $request->message;
$chat->save();
event( new GetMessages( $chat ));
My Event class:
class GetMessages implements ShouldBroadcast
{
use Dispatchable, InteractsWithSockets, SerializesModels;
public $chats;
public function __construct($chats)
{
$this->chats = $chats;
}
public function broadcastOn()
{
return ['get-messages'];
}
public function broadcastAs()
{
return 'get-messages';
}
}
Here is my Laravel Echo
Echo.channel('get-messages')
.listen('.get-messages', (data) => {
console.log(data)
})
Everything is working fine as I expected, except getting the attachments
from the Chat
.
console.log(data.chats); // Undefined
Is there something I missed? Because as I tested the eager-loaded
from the Event class itself, I can access the attachments
in there.
public $chats;
public function __construct($chats)
{
$this->chats = $chats;
echo $chats->attachments // It's working in here, I can get the attachments
}
Hope I explain it well, Thank you in advance
Cheers!
Here is the console.log
Here is use
, it's the default when I created the Event
namespace App\Events;
use Illuminate\Broadcasting\Channel;
use Illuminate\Queue\SerializesModels;
use Illuminate\Broadcasting\PrivateChannel;
use Illuminate\Broadcasting\PresenceChannel;
use Illuminate\Foundation\Events\Dispatchable;
use Illuminate\Broadcasting\InteractsWithSockets;
use Illuminate\Contracts\Broadcasting\ShouldBroadcast;
class GetMessages implements ShouldBroadcast
{
use Dispatchable, InteractsWithSockets, SerializesModels;
...