46 lines
1.3 KiB
PHP
46 lines
1.3 KiB
PHP
<?php
|
|
|
|
namespace App\Actions;
|
|
|
|
use App\Events\MessageSent;
|
|
use App\Exceptions\MessageNotSendException;
|
|
use App\Models\User;
|
|
use DB;
|
|
|
|
final readonly class SendMessageAction
|
|
{
|
|
public function __construct(private CreateOrGetInboxAction $inboxAction) {}
|
|
|
|
/**
|
|
* @throws \Throwable
|
|
*/
|
|
public function execute(User $sender, User $recipient, array $data): void
|
|
{
|
|
try {
|
|
|
|
// find the inbox between the two users
|
|
DB::beginTransaction();
|
|
$inbox = $this->inboxAction->execute($recipient, $sender);
|
|
|
|
// update the inbox with the last message and last user as current user
|
|
$inbox->last_message = $data['message'];
|
|
$inbox->last_user_id = $sender->id;
|
|
$inbox->save();
|
|
|
|
// create a new message in the inbox
|
|
$message = $inbox->messages()->create([
|
|
'message' => $data['message'],
|
|
'user_id' => $sender->id,
|
|
]);
|
|
|
|
// Send the message to all other users in the inbox
|
|
broadcast(new MessageSent($message))->toOthers();
|
|
|
|
DB::commit();
|
|
} catch (\Throwable $e) {
|
|
DB::rollBack();
|
|
throw new MessageNotSendException('Message not sent.', previous: $e);
|
|
}
|
|
}
|
|
}
|