PHP code example of martinko366 / laravel-db-chat

1. Go to this page and download the library: Download martinko366/laravel-db-chat library. Choose the download type require.

2. Extract the ZIP file and open the index.php.

3. Add this code to the index.php.
    
        
<?php
require_once('vendor/autoload.php');

/* Start to develop here. Best regards https://php-download.com/ */

    

martinko366 / laravel-db-chat example snippets


// config/dbchat.php
'route' => [
    'prefix' => 'api/dbchat',
    'middleware' => ['api', 'auth:sanctum'],
],

use Symfony\Component\HttpFoundation\StreamedResponse;

class SSEController extends Controller
{
    public function __invoke(Request $request, MessageService $messageService)
    {
        return new StreamedResponse(function () use ($request, $messageService) {
            $lastMessageId = $request->query('after_message_id', 0);
            $conversationIds = // ... get user's conversation IDs

            while (true) {
                $messages = $messageService->getNewMessages($conversationIds, $lastMessageId);
                
                if ($messages->isNotEmpty()) {
                    echo "data: " . json_encode([
                        'last_message_id' => $messages->last()->id,
                        'messages' => $messages,
                    ]) . "\n\n";
                    
                    ob_flush();
                    flush();
                    
                    $lastMessageId = $messages->last()->id;
                }
                
                sleep(1);
            }
        }, 200, [
            'Content-Type' => 'text/event-stream',
            'Cache-Control' => 'no-cache',
            'X-Accel-Buffering' => 'no',
        ]);
    }
}
bash
php artisan vendor:publish --tag=dbchat-config
php artisan vendor:publish --tag=dbchat-migrations
bash
php artisan migrate
json
{
  "conversation": {
    "id": 1,
    "type": "direct",
    "title": null,
    "created_at": "2024-01-01T00:00:00.000000Z"
  }
}