Weave Code
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

Laravel Onesignal Laravel Package

lepresk/laravel-onesignal

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Steps

  1. 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
    
  2. 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]);
        }
    }
    
  3. Send Notification:

    $user = User::find(1);
    $user->notify(new OrderReceivedNotification($order));
    

Where to Look First

  • Configuration: config/onesignal.php (published via vendor:publish)
  • Notification Builder: Lepresk\OneSignal\OneSignalMessage (fluent API)
  • Events: Lepresk\OneSignal\Events (for lifecycle hooks)
  • Exceptions: Lepresk\OneSignal\Exceptions (custom error handling)

First Use Case

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; }
});

Implementation Patterns

Core Workflows

1. Basic Notification Flow

// 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());

2. Segmented Notifications

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'
    ]);

3. Rich Media Notifications

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');

4. Event-Driven Notifications

Listen to notification lifecycle events:

// In EventServiceProvider
protected $listen = [
    'Lepresk\OneSignal\Events\NotificationSent' => [
        \App\Listeners\LogNotification::class,
    ],
];

5. Bulk Notifications

Send to all subscribers (use cautiously):

$message = OneSignalMessage::create()
    ->setTitle('System Alert')
    ->setBody('Maintenance in 1 hour');

OneSignal::send($message); // Direct API call

Integration Tips

Laravel Notifications

  • Extend OneSignalNotification for type safety and IDE support.
  • Use Notifiable trait on models:
    use Lepresk\OneSignal\Notifiable;
    class User extends Authenticatable { use Notifiable; }
    

API Rate Limiting

  • OneSignal has request limits (e.g., 1000 messages/minute).
  • Implement queueing for bulk sends:
    $user->notify(new MyNotification())->onQueue('high');
    

Testing

  • Use mock HTTP client in tests:
    $this->mock(OneSignalClient::class, function ($mock) {
        $mock->shouldReceive('send')->once();
    });
    

Webhooks

  • Configure OneSignal webhooks in your dashboard to receive delivery reports.
  • Handle webhook payloads in Laravel:
    Route::post('/onesignal/webhook', [OneSignalWebhookHandler::class, 'handle']);
    

Gotchas and Tips

Pitfalls

  1. API Key Exposure:

    • Never commit .env with ONESIGNAL_REST_API_KEY.
    • Use Laravel’s environment variables or vault (e.g., Laravel Forge, Envoyer).
  2. Rate Limits:

    • OneSignal throttles requests. Queue notifications for large audiences.
    • Monitor logs for 429 Too Many Requests errors.
  3. Device Tokens:

    • Player IDs (not FCM/APNs tokens) are used for targeting.
    • Ensure tokens are valid and up-to-date in OneSignal dashboard.
  4. Payload Size Limits:

    • OneSignal enforces a 32KB payload limit. Avoid sending large JSON data.
    • Use short-lived URLs or database IDs for deep links.
  5. Time Zones:

    • OneSignal uses UTC for scheduled notifications. Adjust created_at in Laravel:
    $message->setSendAfter('+1 hour')->setSendAfterTimeZone('America/New_York');
    

Debugging

  • 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

Configuration Quirks

  1. Default Values:

    • config/onesignal.php has sensible defaults (e.g., timeout=10 seconds).
    • Override only what’s necessary.
  2. 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')));
    
  3. Custom HTTP Client: Override the default Guzzle client:

    // config/onesignal.php
    'http_client' => \App\Services\CustomGuzzleClient::class,
    

Extension Points

  1. 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]);
        }
    }
    
  2. Webhook Handlers: Extend OneSignalWebhookHandler:

    class CustomWebhookHandler extends OneSignalWebhookHandler {
        protected function handleDeliveryReport(array $payload) {
            // Custom logic for failed/sent notifications
        }
    }
    
  3. Notification Events: Dispatch custom events:

    event(new NotificationSent($notifiable, $message));
    
  4. Fallback Channels: Combine with other channels (e.g., email) in via():

    public function via($notifiable) {
        return ['mail', 'onesignal'];
    }
    

Performance Tips

  • Batch Player IDs: Send to 1000 IDs max per request (OneSignal limit).
    $message->setIncludePlayerIds(array_chunk($playerIds, 1000));
    
  • Reuse Message Objects: Instantiate OneSignalMessage once and reuse it for similar notifications.
  • Lazy-Load Data: Fetch dynamic data (e.g., user
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.
daikazu/eloquent-salesforce-objects
unseen-codes/chat
romalytar/yammi-jobs-monitoring-laravel
kisame76/filament-db-table-state
nqxcode/laravel-lucene-search
dpfx/laravel-livewire-wizards
workos/workos-php-laravel
sofa/laravel-global-scope
nawasara/auth-primitives
adhocrat-io/arkhe-main
make-dev/orca-harpoon
itsemon245/lamet
baks-dev/dashboard
amoifr/pickle-panther-bundle
make-dev/orca
dmstr/symfony-system-resources-bundle
dmstr/symfony-job-queue-bundle
dmstr/openapi-json-schema-bundle
dmstr/keycloak-security-bundle
dmstr/doctrine-audit-log-bundle