Downloads
Stars
Version
Adds chat functionality for your project on top of Laravel Broadcasting feature.
Lower versions are not supported.
saritasa/laravel-chat-api
package:bash $ composer require saritasa/laravel-chat-api
Publish config with
bash $ artisan vendor:publish --tag=laravel_chat_api
Update config/laravel_chat_api.php sections:
userModelClass
.Configure at least one broadcasting driver
$chatService->createChat($creator, ['name' => 'New Chat'], [1, 2]);
Where [1, 2] - identifiers of participants of chat excluded creator.
$chatService->closeChat($creator, $chat);
Remember that only creator can close chat and can't close "already closed" chat. In this cases ChatException will be
thrown.
$chatService->leaveChat($user, $chat);
When creator leaves chat on of participants became to creator.
$chatService->sendMessage($sender, $chat, $message);
$chatService->markChatAsRead($chat, $user);
Throws in chat channel for all subscribers who participate in chatting.
Throws in user channel for all subscribers who participate in chatting exclude event initiator.
To integrate it with Laravel broadcasting you can just update your broadcasting routes file ( routes/channels.php by default ) with next example:
...
use Saritasa\LaravelChatApi\Events\ChatCreatedEvent;
use Saritasa\LaravelChatApi\Events\ChatEvent;
use Saritasa\LaravelChatApi\Contracts\IChatUser;
...
// Using model binding for chat events channel.
Broadcast::channel(ChatEvent::CHANNEL_PREFIX . '{chat}', function ($user, Chat $chat) {
// Checking that auth user is chat participant.
return $chat->getUsers()->pluck('id')->contains($user->id);
});
Broadcast::channel(ChatCreatedEvent::CHANNEL_PREFIX . '{id}', function ($user, int $id) {
return (int)$user->id === $id;
});
Read in official documentation about defining authorization callbacks. Now all chat events will dispatch through your broadcast driver.
To easy sent notifications you should create your own notification and update laravel_chat_api.php
config file.
Here is example if we should send notification when chat was reopened:
return [
...
'notifications' => [
...
'chatReopened' => App\Notifications\MyOwnChatReopenedNotification::class,
],
];