PHP code example of syriable / laravel-messenger

1. Go to this page and download the library: Download syriable/laravel-messenger 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/ */

    

syriable / laravel-messenger example snippets


use Illuminate\Database\Eloquent\Model;
use Syriable\Messenger\Contracts\MessengerParticipant;
use Syriable\Messenger\Support\Messageable;

class User extends Model implements MessengerParticipant
{
    use Messageable;
}

// AppServiceProvider::boot() — register BEFORE the first `php artisan migrate`
use Illuminate\Database\Eloquent\Relations\Relation;

Relation::enforceMorphMap([
    'user' => \App\Models\User::class,
    'agent' => \App\Models\SupportAgent::class,
]);

use Syriable\Messenger\Facades\Messenger;

// Body only
$message = Messenger::send($alice, $bob, 'Hey Bob!');

// Via the participant model
$alice->sendMessageTo($bob, 'Hey Bob!');

// Attachments only, or body + attachments + a reply reference
$alice->sendMessageTo($bob, [
    'body' => 'Here is the file',
    'attachments' => [$request->file('document')],
    'reply_to' => $previousMessage, // or a message id
]);

// Inbox, ordered by latest activity (unread never reorders it)
$conversations = $alice->inbox();
$conversations = $alice->inbox(['rs is N+1-free (see below).
$conversations = $alice->inbox(['with_participant_models' => true]);

// Blocked/spam threads stay in the inbox by design (history is preserved); drop
// them explicitly if your UI hides them.
$conversations = $alice->inbox(['exclude_blocked' => true, 'exclude_spam' => true]);

// Messages, chronological (newest at the bottom), respecting the viewer's cleared history
$conversation = Messenger::between($alice, $bob);
$messages = Messenger::messages($conversation, $alice, ['limit' => 50]);

// Keyset pagination for large conversations (mutually exclusive cursors):
// load the most recent page on open, then the previous page as the user scrolls up.
$latest = Messenger::messages($conversation, $alice, ['limit' => 50]);
$older  = Messenger::messages($conversation, $alice, ['before_id' => $latest->first()->id, 'limit' => 50]);
$newer  = Messenger::messages($conversation, $alice, ['after_id' => $latest->last()->id, 'limit' => 50]);

// ⚠ Always pass `limit`. Omitting it loads the **entire** visible history into memory.
// That is intentional for scripts, but almost never right for HTTP or Livewire endpoints.
// For production, set `messenger.messages.max_read_limit` to a hard page-size ceiling:
// it caps any provided `limit` AND bounds an omitted one, so a forgotten `limit`
// can never hydrate a whole conversation.

// Unread totals (denormalized — no message scanning; archived excluded by default)
$alice->unreadMessagesCount();               // total unread messages
$alice->unreadConversationsCount();          // number of conversations with unread
Messenger::unreadCount($alice);              // total unread messages
Messenger::unreadConversations($alice);      // number of conversations with unread
Messenger::unreadCount($alice, 

Messenger::archive($conversation, $alice);     // and ->unarchive(...)
Messenger::star($conversation, $alice);        // and ->unstar(...)
Messenger::block($conversation, $alice);       // mutual; ->unblock(...)
Messenger::spam($conversation, $alice);        // mutual; ->unspam(...)
Messenger::clear($conversation, $alice);       // visibility reset, no deletion
Messenger::markAsRead($conversation, $alice);  // opening a conversation reads it
Messenger::markAsUnread($conversation, $alice);// sets unread_count to 1 (not the true historical count)

Messenger::report($message, $reporter, reason: 'spam', note: 'Unsolicited link');

use Syriable\Messenger\Exceptions\MessengerException;

try {
    Messenger::send($from, $to, $payload);
} catch (MessengerException $e) {
    // Catches every package exception above. Catch specific subclasses first
    // if you want different status codes or messages per failure.
    return redirect()
        ->route('conversations.show', $conversation)
        ->withErrors(['message' => $e->getMessage()]);
}

// config/messenger.php
'broadcasting' => [
    'enabled' => env('MESSENGER_BROADCASTING_ENABLED', false),
    'channel_prefix' => 'messenger',
    'private' => true,
],

// routes/channels.php (host application)
use Syriable\Messenger\Models\Conversation;

Broadcast::channel('messenger.conversation.{conversationId}', function ($user, string $conversationId) {
    $conversation = Conversation::find($conversationId);

    return $conversation
        && $conversation->participants()
            ->where('participant_type', $user->getMorphClass())
            ->where('participant_id', $user->getKey())
            ->exists();
});

// config/messenger.php
'pipeline' => [
    \Syriable\Messenger\Pipelines\Send\EnsureParticipantsAreValid::class,
    \Syriable\Messenger\Pipelines\Send\EnsureParticipantsExist::class,
    \Syriable\Messenger\Pipelines\Send\EnsureConversationIsNotBlocked::class,
    \Syriable\Messenger\Pipelines\Send\EnsureMessageHasContent::class,
    \Syriable\Messenger\Pipelines\Send\EnsureAttachmentsAreValid::class,
    \Syriable\Messenger\Pipelines\Send\EnsureReplyIsValid::class,
    \App\Messaging\ProfanityFilter::class, // your own SendPipe
],

use Closure;
use Syriable\Messenger\Contracts\SendPipe;
use Syriable\Messenger\Data\PendingMessage;

class ProfanityFilter implements SendPipe
{
    public function handle(PendingMessage $message, Closure $next): PendingMessage
    {
        // inspect / mutate / reject, then:
        return $next($message);
    }
}

Messenger::pruneAttachments();              // delete and return
Messenger::pruneAttachments(dryRun: true);  // list only

// config/database.php — sqlite connection
'options' => [PDO::ATTR_TIMEOUT => 5], // seconds to wait on a locked database
// and run once: PRAGMA journal_mode=WAL;
bash
php artisan vendor:publish --tag="messenger-migrations"
php artisan migrate
bash
php artisan vendor:publish --tag="messenger-config"