bhhaskin / laravel-webpush
Web push notification channel for Laravel. VAPID-signed browser push delivered via Laravel's Notification system.
Requires
- php: ^8.1
- illuminate/database: ^10.0|^11.0|^12.0|^13.0
- illuminate/notifications: ^10.0|^11.0|^12.0|^13.0
- illuminate/routing: ^10.0|^11.0|^12.0|^13.0
- illuminate/support: ^10.0|^11.0|^12.0|^13.0
- minishlink/web-push: ^9.0|^10.0
Requires (Dev)
- orchestra/testbench: ^8.0|^9.0|^10.0|^11.0
- pestphp/pest: ^2.0|^3.0|^4.0
- phpunit/phpunit: ^10.5|^11.0|^12.0
README
Web Push notification channel for Laravel. Sends VAPID-signed browser push notifications via Laravel's standard Notification system. Subscriptions are polymorphic, so any model (not just User) can be notified.
Built on minishlink/web-push.
Installation
composer require bhhaskin/laravel-webpush
Publish and run the migration:
php artisan vendor:publish --tag=webpush-migrations php artisan migrate
Optionally publish the config:
php artisan vendor:publish --tag=webpush-config
VAPID keys
Generate a keypair once per deployment:
vendor/bin/web-push generate-vapid-keys
Add to your .env:
VAPID_SUBJECT="mailto:you@example.com" VAPID_PUBLIC_KEY="..." VAPID_PRIVATE_KEY="..."
The public key is also served to the browser by GET /api/push-subscriptions/vapid-key.
Setup
Add the HasPushSubscriptions trait to any notifiable model:
use Bhhaskin\LaravelWebpush\Concerns\HasPushSubscriptions; use Illuminate\Foundation\Auth\User as Authenticatable; use Illuminate\Notifications\Notifiable; class User extends Authenticatable { use Notifiable; use HasPushSubscriptions; }
The trait adds pushSubscriptions(), addPushSubscription(), removePushSubscription(), and routeNotificationForWebpush(). The last is what Laravel's notification system calls to resolve delivery targets.
Sending a notification
Define toWebPush() on your notification and include 'webpush' in via():
use Bhhaskin\LaravelWebpush\Messages\WebPushMessage; use Illuminate\Notifications\Notification; class OrderShipped extends Notification { public function __construct(public int $orderId) {} public function via($notifiable): array { return ['webpush']; } public function toWebPush($notifiable): WebPushMessage { return WebPushMessage::create('Your order shipped') ->body('Tracking is available in your dashboard.') ->icon('/icons/package.png') ->tag("order-{$this->orderId}") ->url("/orders/{$this->orderId}"); } }
Send it exactly like any other notification:
$user->notify(new OrderShipped($order->id));
The channel fans out to every PushSubscription attached to the notifiable.
Message builder
WebPushMessage is a fluent builder for the payload your service worker receives:
WebPushMessage::create('Title', 'Body') ->icon('/icons/icon-192.png') ->badge('/icons/badge-96.png') ->image('/images/hero.png') ->tag('unique-tag') // replaces prior notifications with the same tag ->url('/path/to/open') // read in the SW click handler via event.notification.data.url ->requireInteraction() ->renotify() ->vibrate([200, 100, 200]) ->action('done', 'Done', '/icons/done.png') ->action('snooze', 'Snooze') ->withData(['conversation_id' => 42]) ->ttl(3600) // sending option, not payload ->urgency('high') ->topic('chat-42');
toPayload() returns the JSON object delivered to the service worker. getOptions() returns the Web Push protocol options (TTL, urgency, topic) forwarded to the push service.
HTTP endpoints
When webpush.routes.enabled is true (the default), three routes are registered:
| Method | Path | Purpose |
|---|---|---|
| GET | /api/push-subscriptions/vapid-key |
Returns the public VAPID key |
| POST | /api/push-subscriptions |
Subscribe the authenticated notifiable |
| DELETE | /api/push-subscriptions |
Unsubscribe by endpoint |
POST body:
{
"endpoint": "https://fcm.googleapis.com/fcm/send/...",
"keys": { "p256dh": "...", "auth": "..." }
}
Configure prefix, middleware, or controller in config/webpush.php. Set routes.enabled to false and mount PushSubscriptionController yourself if you need multiple guards or different paths.
Client-side
Subscribe from the browser and post the subscription to /api/push-subscriptions:
const { vapid_key } = await fetch('/api/push-subscriptions/vapid-key').then(r => r.json()); const registration = await navigator.serviceWorker.register('/sw.js'); await Notification.requestPermission(); const subscription = await registration.pushManager.subscribe({ userVisibleOnly: true, applicationServerKey: urlBase64ToUint8Array(vapid_key), }); await fetch('/api/push-subscriptions', { method: 'POST', headers: { 'Content-Type': 'application/json', 'Accept': 'application/json' }, body: JSON.stringify(subscription.toJSON()), }); function urlBase64ToUint8Array(base64String) { const padding = '='.repeat((4 - base64String.length % 4) % 4); const base64 = (base64String + padding).replace(/-/g, '+').replace(/_/g, '/'); const raw = atob(base64); return Uint8Array.from([...raw].map(c => c.charCodeAt(0))); }
A minimal service worker handler for the payload shape emitted by WebPushMessage::toPayload():
self.addEventListener('push', (event) => { const data = event.data?.json() ?? {}; event.waitUntil(self.registration.showNotification(data.title ?? '', { body: data.body, icon: data.icon, badge: data.badge, image: data.image, tag: data.tag, actions: data.actions, requireInteraction: data.requireInteraction, renotify: data.renotify, silent: data.silent, vibrate: data.vibrate, data: { url: data.url, ...(data.data ?? {}) }, })); }); self.addEventListener('notificationclick', (event) => { event.notification.close(); const url = event.notification.data?.url; if (!url) return; event.waitUntil(clients.openWindow(url)); });
Expired subscription handling
When a push service returns 404 or 410 for a subscription, the channel dispatches Bhhaskin\LaravelWebpush\Events\PushSubscriptionExpired and, unless webpush.prune_expired is false, deletes the row. Listen for the event if you need to log, notify, or take other action before the row is removed.
Configuration reference
See config/webpush.php after publishing. Key options:
vapid.subject/vapid.public_key/vapid.private_key: requiredmodel/table: swap the Eloquent model or table nameroutes.enabled/routes.prefix/routes.middleware/routes.controlleroptions.TTL/options.urgency/options.topic: per-request defaultsprune_expired: delete rows when push services report the subscription is gone
Testing
composer test