Installation:
composer require lepresk/laravel-onesignal
php artisan vendor:publish --tag=onesignal-config
Add OneSignal credentials to .env:
ONESIGNAL_APP_ID=your_app_id
ONESIGNAL_REST_API_KEY=your_rest_key
First Notification:
Create a notification class extending OneSignalNotification:
use Lepresk\OneSignal\OneSignalNotification;
class OrderReceivedNotification extends OneSignalNotification
{
public function via($notifiable)
{
return ['onesignal'];
}
public function toOneSignal($notifiable)
{
return OneSignalMessage::create()
->setTitle('New Order Received')
->setBody('Order #'.$notifiable->order_id.' is ready!')
->setData(['order_id' => $notifiable->order_id]);
}
}
Send Notification:
$user = User::find(1);
$user->notify(new OrderReceivedNotification($order));
config/onesignal.php (published via vendor:publish)Lepresk\OneSignal\OneSignalMessage (fluent API)Lepresk\OneSignal\Events (for lifecycle hooks)Lepresk\OneSignal\Exceptions (custom error handling)Send a targeted push notification to specific devices/users:
$message = OneSignalMessage::create()
->setTitle('Hello!')
->setBody('Check this out')
->setIncludePlayerIds(['player_id_1', 'player_id_2']); // Target specific devices
$notifiable->notify(new class($message) extends OneSignalNotification {
public function toOneSignal($notifiable) { return $this->message; }
});
// 1. Define notification
class MyNotification extends OneSignalNotification {
public function via($notifiable) { return ['onesignal']; }
public function toOneSignal($notifiable) {
return OneSignalMessage::create()
->setTitle('Alert')
->setBody('Something happened!')
->setData(['key' => 'value']);
}
}
// 2. Trigger notification
$user->notify(new MyNotification());
Use OneSignal’s filters to target specific audiences:
$message = OneSignalMessage::create()
->setTitle('Exclusive Offer')
->setBody('Only for VIP users!')
->setFilter([
'fields' => ['tag:user_type', 'in', ['vip', 'premium']],
'operator' => 'AND'
]);
Attach images, buttons, or deep links:
$message = OneSignalMessage::create()
->setTitle('New Update')
->setBody('Check out our latest feature!')
->addButton('View', '#', 'view_button')
->addImage('https://example.com/image.jpg')
->setUrl('https://example.com/dashboard');
Listen to notification lifecycle events:
// In EventServiceProvider
protected $listen = [
'Lepresk\OneSignal\Events\NotificationSent' => [
\App\Listeners\LogNotification::class,
],
];
Send to all subscribers (use cautiously):
$message = OneSignalMessage::create()
->setTitle('System Alert')
->setBody('Maintenance in 1 hour');
OneSignal::send($message); // Direct API call
OneSignalNotification for type safety and IDE support.Notifiable trait on models:
use Lepresk\OneSignal\Notifiable;
class User extends Authenticatable { use Notifiable; }
$user->notify(new MyNotification())->onQueue('high');
$this->mock(OneSignalClient::class, function ($mock) {
$mock->shouldReceive('send')->once();
});
Route::post('/onesignal/webhook', [OneSignalWebhookHandler::class, 'handle']);
API Key Exposure:
.env with ONESIGNAL_REST_API_KEY.Rate Limits:
429 Too Many Requests errors.Device Tokens:
Payload Size Limits:
Time Zones:
created_at in Laravel:$message->setSendAfter('+1 hour')->setSendAfterTimeZone('America/New_York');
Enable Logging:
Configure config/onesignal.php:
'log' => [
'enabled' => true,
'channel' => 'single',
],
Logs appear in storage/logs/laravel.log.
Inspect Raw Payload:
$message = (new MyNotification($user))->toOneSignal($user);
\Log::debug('OneSignal Payload:', $message->toArray());
Common Errors:
| Error | Cause | Fix |
|---|---|---|
Invalid API Key |
Wrong ONESIGNAL_REST_API_KEY |
Verify .env and OneSignal dashboard |
Invalid Player ID |
Stale or incorrect device token | Re-register devices |
Payload too large |
Exceeds 32KB limit | Reduce data or use URLs |
Notification not delivered |
App not configured in OneSignal | Check platform settings in dashboard |
Default Values:
config/onesignal.php has sensible defaults (e.g., timeout=10 seconds).Environment-Specific Config: Use Laravel’s config caching:
php artisan config:cache
For local/staging/prod differences, use:
config('onesignal.app_id', env('ONESIGNAL_APP_ID', config('onesignal.app_id')));
Custom HTTP Client: Override the default Guzzle client:
// config/onesignal.php
'http_client' => \App\Services\CustomGuzzleClient::class,
Custom Message Builder:
Extend OneSignalMessage for domain-specific methods:
class MarketingMessage extends OneSignalMessage {
public function setPromoCode(string $code): self {
return $this->addData(['promo_code' => $code]);
}
}
Webhook Handlers:
Extend OneSignalWebhookHandler:
class CustomWebhookHandler extends OneSignalWebhookHandler {
protected function handleDeliveryReport(array $payload) {
// Custom logic for failed/sent notifications
}
}
Notification Events: Dispatch custom events:
event(new NotificationSent($notifiable, $message));
Fallback Channels:
Combine with other channels (e.g., email) in via():
public function via($notifiable) {
return ['mail', 'onesignal'];
}
$message->setIncludePlayerIds(array_chunk($playerIds, 1000));
OneSignalMessage once and reuse it for similar notifications.How can I help you explore Laravel packages today?