Files
backend-mm/app/Events/Conversation/MessageSent.php

65 lines
1.6 KiB
PHP

<?php
namespace App\Events\Conversation;
use App\Http\Controllers\Api\V1\Chat\Resources\MessageResource;
use App\Models\Chat\Message;
use Illuminate\Broadcasting\Channel;
use Illuminate\Broadcasting\InteractsWithSockets;
use Illuminate\Broadcasting\PrivateChannel;
use Illuminate\Contracts\Broadcasting\ShouldBroadcast;
use Illuminate\Foundation\Events\Dispatchable;
use Illuminate\Queue\SerializesModels;
class MessageSent implements ShouldBroadcast
{
use Dispatchable, InteractsWithSockets, SerializesModels;
/**
* Create a new event instance.
*/
public function __construct(private Message $message)
{
$this->message->loadMissing('user');
}
/**
* Get the channels the event should broadcast on.
*
* @return array<int, Channel>
*/
public function broadcastOn(): array
{
$channels = [
new PrivateChannel('chat.'.$this->message->conversation_id),
];
$supportId = (int) config('chat.support_user_id');
if ($supportId > 0) {
$isSupportConversation = $this->message->conversation()
->whereHas('users', fn ($query) => $query->where('users.id', $supportId))
->exists();
if ($isSupportConversation) {
$channels[] = new PrivateChannel('chat.support');
}
}
return $channels;
}
public function broadcastAs(): string
{
return 'message.sent';
}
/**
* @return array<string, mixed>
*/
public function broadcastWith(): array
{
return (new MessageResource($this->message->loadMissing('user')))->resolve();
}
}