Weave Code
Weaver
Helps Laravel developers discover, compare, and choose open-source packages. See popularity, security, maintainers, and scores at a glance to make better decisions.
Feedback
Share your thoughts, report bugs, or suggest improvements.
Subject
Message

Pubnub Laravel Package

laravel-notification-channels/pubnub

Send Laravel notifications through PubNub realtime messaging. This channel publishes notification payloads to PubNub channels so subscribed clients receive instant updates over WebSockets, with support for per-notifier channel names and publish options.

View on GitHub
Deep Wiki
Context7

Getting Started

1. Check compatibility before committing. The last release was October 2019, which predates Laravel 7+. Expect it to target Laravel 5.8/6 and PHP 7.x. Try:

composer require laravel-notification-channels/pubnub

If dependency resolution explodes on a modern app (usually a pubnub/pubnub SDK ↔ Guzzle conflict or a missing illuminate/support constraint), fall back to --with-all-dependencies, pinning the SDK yourself, or forking the package — it is small enough to vendor.

2. Configure credentials. PubNub needs a publish key, subscribe key, and (only for Access Manager / channel-group operations) a secret key. Put them in .env:

PUBNUB_PUBLISH_KEY=pub-c-...
PUBNUB_SUBSCRIBE_KEY=sub-c-...
PUBNUB_SECRET_KEY=sec-c-...

Then wire them into config/services.php under a pubnub key (that is where most community channels resolve credentials). If the package ships its own config file, run:

php artisan vendor:publish --provider="NotificationChannels\Pubnub\PubnubServiceProvider"

and clear the config cache with php artisan config:cache after editing.

3. Where to look first.

  • README.md — sparse, but confirms the method names (toPubnub, PubnubMessage, PubnubChannel).
  • src/PubnubChannel.php — this is the send() implementation; it tells you exactly which PubnubMessage builder methods exist and how the client is resolved from the container.
  • src/PubnubMessage.php — the fluent builder (channel(s), payload, and possibly APNS/GCM push fields).
  • src/PubnubServiceProvider.php — whether the PubNub client is bound as a singleton and under what key, plus whether the package uses auto-discovery.

4. First use case. A one-way "notify this user's device/app" push. Give the notifiable a routing method:

public function routeNotificationForPubnub()
{
    return "user-{$this->id}";
}

…and the first notification:

class OrderShipped extends Notification
{
    public function via($notifiable)
    {
        return [PubnubChannel::class];
    }

    public function toPubnub($notifiable)
    {
        return PubnubMessage::create()
            ->channel($notifiable->routeNotificationForPubnub())
            ->payload(['event' => 'order.shipped', 'order_id' => $this->order->id]);
    }
}

Then $user->notify(new OrderShipped($order));. If that round-trip works, the channel is functional; everything below is scaling it.

Implementation Patterns

Notification class pattern. The channel is a standard Laravel notification driver: via() returns the channel class, toPubnub($notifiable) returns a PubnubMessage. Keep the payload small and schema-stable — subscribers are clients you don't control, so version your payload (v: 1) and treat it as an API contract.

Routing lives on your model. routeNotificationForPubnub() is the cleanest integration point. Common conventions: user-{id} for per-user channels, tenant-{id}-broadcast for broadcast channels, role-{slug} for role-based fan-out. Keep a single method that composes the name so tests and the channel agree.

On-demand notifications. If the channel supports anonymous routing, you can skip a notifiable model:

Notification::route('pubnub', 'user-42')->notify(new SystemAlert($message));

Verify in PubnubChannel.php that it honors $notifiable->routes['pubnub']; if not, use a tiny AnonymousNotifiable-friendly wrapper.

Always queue. PubNub publishes are network calls inside the request cycle. Implement ShouldQueue on the notification, or dispatch the notify() call from a job. Use retryUntil/$tries on the queue job rather than relying on the channel to retry.

Fan-out. PubNub channels are flat — there are no wildcards. For "send to all devices of a user" or "send to everyone in a tenant", either:

  • loop over channel names server-side (one publish each), or
  • maintain a channel group server-side and publish to the group (requires secret key + Access Manager; do this in your own service class, not in the notification).

Push to mobile. If you're targeting APNS/FCM, the message builder usually exposes push-specific payload setters or accepts raw pn_apns / pn_gcm keys inside the payload. Device-token registration and enable push calls are your responsibility — this channel only publishes. Build a small PubnubDeviceRegistrar service around the SDK's push API.

Testing. Use Notification::fake() to assert the notification was sent:

Notification::fake();
$user->notify(new OrderShipped($order));
Notification::assertSentTo($user, OrderShipped::class);

For integration tests, bind a fake client into the container (whatever key PubnubServiceProvider uses) so no real network calls fire. Reserve a real PubNub test keyset for a single smoke test in CI.

Multi-tenant / environment prefixes. Prefix channel names with the app env (staging:user-42) so staging publishes never hit production subscribers. Do it in routeNotificationForPubnub() — one place, easy to audit.

Compose with other channels. This channel is a good supplement to mail/database for real-time UX, not a replacement. Typical via() returns ['database', 'mail', PubnubChannel::class] — the persisted record is your source of truth, PubNub is the "instant" layer.

Gotchas and Tips

Unmaintained — audit before production. 10 stars, 0 dependents, last release 2019. Treat it as sample code, not infrastructure. If you hit a PHP 8 type error or a Laravel 10 method-signature mismatch, you will be patching a fork. Budget an afternoon to read all of src/ — it is a few hundred lines at most. For many teams, a 50-line custom channel around pubnub/pubnub is lower risk than adopting this package.

Secret key handling. Publish/subscribe keys are public (they ship to clients). The secret key is only for Access Manager, channel groups, and push registration. Never include it in client bundles; keep it strictly in .env. If the package resolves credentials lazily from config, php artisan config:cache is required after rotation.

Payload size limits. PubNub caps messages around 32KB. Keep payloads to IDs and event names; let the client fetch the record over HTTP. Oversized payloads fail at the publish call with an unclear error.

Delivery is at-least-once, not exactly-once. Clients can receive duplicates and can miss messages while offline. Carry an idempotency key (notification_id, uuid) in the payload and have clients dedupe. Use PubNub message persistence/history if you need replay.

Errors get swallowed or thrown inconsistently. The channel's send() may not surface a failed publish as an exception. Wrap notification dispatch in a job, log the PubNub response, and treat non-2xx as retryable. Don't assume notify() succeeding means delivery.

Push requires device registration. A common first-day bug: publish "works" but phones never get a push because the device token was never registered with PubNub, or pn_apns/pn_gcm payloads are malformed. Test with the PubNub debug console first, then the Laravel channel — that isolates channel vs. registration problems.

Container binding is your extension point. If the package binds a PubNub client singleton, override it in a service provider ($this->app->singleton(PubNub::class, fn () => new PubNub([...timeouts...]))) to set custom timeouts, TLS, or a mock in tests. That's also the seam for swapping in a self-hosted/mocked PubNub endpoint.

Configure timeouts explicitly. SDK defaults can be long enough to stall a worker. Set connect/read timeouts (5s / 10s is typical) via the client config and pair with queue retryUntil.

Test without Notification::fake() for the channel itself. Notification::fake() proves you called the channel; it doesn't prove the PubNub payload is valid. Add one fake-client test asserting channel name, payload shape, and push keys.

Version your payload contract. Since subscribers are often mobile apps you cannot hot-swap, ship a v field from day one and have clients ignore unknown fields. Changing payload shape without versioning is the most common cause of "notifications randomly stopped working" tickets.

Consider the simpler alternative. If all you need is "user-42 gets a real-time event," a 20-line custom channel that calls PubNub::publish() in a queued job gives you full control, current SDK support, and no abandoned dependency — often the right call here.

Weaver

How can I help you explore Laravel packages today?

Conversation history is not saved when not logged in.
Prompt
Add packages to context
No packages found.
mehedimi/laravel-amp-mail
happones/laravel-vue-i18n-generator
jwerd/inertia-table
siberfx/flysystem-wasabi
hollyit/token-replace
ippanelcom/laravel-sdk
adachsoft/changelog-linter
adachsoft/collection
payerurl/telegrambot-crypto-payment-instant-payout
dskripchenko/laravel-hybrid-search
riorizkyrainey/lara-ced
mehedimi/static-vel
zharp/zharp
nonsapiens/bigquery-model-sync
lgu-bayambang-ict-office/lgu-laravel-development-standards
andydefer/laravel-support
se7enxweb/flysystem
lampwick/laravel
jeslage/statamic-emojis
micahdshackelford/rmap-laravel