Files
Kent-logistics-Laravel/app/Events/NewChatMessage.php
2026-02-17 14:32:48 +05:30

88 lines
2.6 KiB
PHP

<?php
namespace App\Events;
use App\Models\ChatMessage;
use Illuminate\Broadcasting\PrivateChannel;
use Illuminate\Contracts\Broadcasting\ShouldBroadcast;
use Illuminate\Queue\SerializesModels;
class NewChatMessage implements ShouldBroadcast
{
use SerializesModels;
public $message;
/**
* Create a new event instance.
*/
public function __construct(ChatMessage $message)
{
// Safe data only (no heavy relationships in queue)
$this->message = [
'id' => $message->id,
'ticket_id' => $message->ticket_id,
'sender_id' => $message->sender_id,
'sender_type' => $message->sender_type,
'message' => $message->message,
'file_path' => $message->file_path,
'file_type' => $message->file_type,
'created_at' => $message->created_at->toDateTimeString(),
];
// Load sender separately for broadcastWith()
$this->sender = $message->sender;
}
/**
* The channel the event should broadcast on.
*/
public function broadcastOn()
{
return new PrivateChannel('ticket.' . $this->message->ticket_id);
}
/**
* Data sent to frontend (Blade + Flutter)
*/
public function broadcastWith()
{
\Log::info("DEBUG: NewChatMessage broadcasting on channel ticket.".$this->message->ticket_id);
return [
'id' => $this->message->id,
'ticket_id' => $this->message->ticket_id,
'sender_id' => $this->message->sender_id,
'sender_type' => $this->message->sender_type,
'message' => $this->message->message,
'file_url' => $this->message->file_path
? asset('storage/' . $this->message->file_path)
: null,
'file_type' => $this->message->file_type,
'sender' => [
'id' => $this->message->sender->id,
'name' => $this->getSenderName(),
'is_admin' => $this->message->sender_type === \App\Models\Admin::class,
],
'created_at' => $this->message->created_at->toDateTimeString(),
];
}
/**
* Helper to extract sender name
*/
private function getSenderName()
{
$sender = $this->message->sender;
// User has customer_name (in your app)
if ($this->message->sender_type === \App\Models\User::class) {
return $sender->customer_name ?? $sender->name ?? "User";
}
// Admin model has ->name
return $sender->name ?? "Admin";
}
}