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

Onesignal Laravel Laravel Package

berkayk/onesignal-laravel

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Installation:

    composer require berkayk/onesignal-laravel
    

    For Laravel <5.5, add the service provider and facade alias to config/app.php as shown in the README.

  2. Configuration: Publish the config file:

    php artisan vendor:publish --provider="Berkayk\OneSignal\OneSignalServiceProvider" --tag="config"
    

    Update .env with your OneSignal credentials:

    ONESIGNAL_APP_ID=your_app_id
    ONESIGNAL_REST_API_KEY=your_rest_api_key
    
  3. First Use Case: Send a notification to all users:

    use OneSignal;
    
    OneSignal::sendNotification([
        'contents' => ['en' => 'Hello from Laravel!'],
        'headings' => ['en' => 'Notification Title'],
    ]);
    

Implementation Patterns

Core Workflows

  1. Sending Notifications:

    • To All Users:
      OneSignal::sendNotification([
          'contents' => ['en' => 'Your message'],
          'headings' => ['en' => 'Alert'],
          'included_segments' => ['Active Users'], // Optional: Target segments
      ]);
      
    • To Specific Users:
      OneSignal::sendNotificationToUsers([
          'contents' => ['en' => 'Personalized message'],
          'headings' => ['en' => 'Hi, User!'],
          'include_player_ids' => ['player_id_1', 'player_id_2'], // Device IDs
      ]);
      
    • With Data Payload:
      OneSignal::sendNotification([
          'contents' => ['en' => 'New data available'],
          'data' => ['key' => 'value'], // Custom key-value pairs
      ]);
      
  2. Subscription Management:

    • Subscribe a user (device) to a segment:
      OneSignal::subscribeToSegment('player_id_123', 'Premium Users');
      
    • Unsubscribe:
      OneSignal::unsubscribeFromSegment('player_id_123', 'Premium Users');
      
  3. Event Handling: Use Laravel events to trigger notifications (e.g., after user registration):

    // In UserObserver.php
    public function created(User $user) {
        OneSignal::sendNotification([
            'contents' => ['en' => 'Welcome!'],
            'headings' => ['en' => 'New User'],
        ]);
    }
    
  4. Queue Integration: Offload notifications to a queue (e.g., database or redis) for async processing:

    OneSignal::sendNotification([...], true); // Second param: queue
    

Integration Tips

  1. Dynamic Content: Use Laravel Blade or variables to personalize notifications:

    $user = auth()->user();
    OneSignal::sendNotification([
        'contents' => ['en' => "Hello, {$user->name}!"],
    ]);
    
  2. Localization: Support multiple languages via OneSignal’s contents and headings arrays:

    OneSignal::sendNotification([
        'contents' => [
            'en' => 'English message',
            'tr' => 'Türkçe mesaj',
        ],
        'headings' => [
            'en' => 'English Title',
            'tr' => 'Türkçe Başlık',
        ],
    ]);
    
  3. Testing: Use a sandbox OneSignal app (e.g., ONESIGNAL_APP_ID=sandbox) and mock responses in tests:

    // In tests/CreatesApplication.php
    $this->app->singleton(OneSignal::class, function () {
        return Mockery::mock(OneSignal::class)->shouldReceive('sendNotification')->once()->andReturn(true);
    });
    
  4. Logging: Enable debug logging in config/onesignal.php:

    'debug' => env('ONESIGNAL_DEBUG', false),
    

    Check Laravel logs for API response details.


Gotchas and Tips

Pitfalls

  1. Rate Limits: OneSignal enforces rate limits. Cache frequent notifications or batch sends:

    // Batch send to 100 users at a time
    $players = User::pluck('player_id')->chunk(100);
    foreach ($players as $chunk) {
        OneSignal::sendNotificationToUsers([...], $chunk->toArray());
    }
    
  2. Player ID Management:

    • Player IDs are device-specific. Ensure they’re stored in your DB (e.g., users table) and updated via OneSignal’s SDK.
    • Gotcha: Hardcoding IDs or not validating them can lead to silent failures.
  3. Configuration Overrides:

    • The package respects .env but also allows runtime overrides:
      OneSignal::setAppId('temp_app_id'); // Override temporarily
      
  4. Async Failures:

    • Queued notifications may fail silently. Implement a retry mechanism or monitor the failed_jobs table.

Debugging

  1. API Errors: Enable debug mode (ONESIGNAL_DEBUG=true) to log raw API responses. Common errors:

    • 401 Unauthorized: Invalid REST_API_KEY or APP_ID.
    • 429 Too Many Requests: Hit rate limits (check OneSignal docs).
  2. Testing Locally: Use a tool like ngrok to expose your localhost for OneSignal webhook testing.

Extension Points

  1. Custom Endpoints: Extend the OneSignal facade to add custom API calls:

    // In app/Providers/AppServiceProvider.php
    public function boot() {
        OneSignal::extend('custom', function ($params) {
            return $this->client->post('/custom_endpoint', $params);
        });
    }
    

    Usage:

    OneSignal::custom(['key' => 'value']);
    
  2. Event Listeners: Listen for OneSignal webhooks (e.g., subscription changes) via Laravel’s HandleIncomingWebhook:

    // routes/web.php
    Route::post('/onesignal/webhook', [OneSignalWebhookHandler::class, 'handle']);
    
  3. Service Provider Binding: Override the default HTTP client for testing or custom logic:

    // In config/app.php
    'bindings' => [
        Berkayk\OneSignal\OneSignal::class => function ($app) {
            return new CustomOneSignalClient($app['http']);
        },
    ];
    

Performance Tips

  1. Bulk Operations: Use OneSignal’s batch APIs for large user groups:

    OneSignal::sendBatchNotification($players, [...]);
    
  2. Caching: Cache segment lists or player IDs to avoid repeated API calls:

    $segment = Cache::remember("onesignal_segment_{$name}", now()->addHours(1), function () use ($name) {
        return OneSignal::getSegmentPlayers($name);
    });
    
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.
hamzi/corewatch
minionfactory/raw-hydrator
hexters/coinpayment
rjcodes/rjcms
act-training/laravel-permissions-manager
alimarchal/laravel-chart-of-accounts
babenkoivan/elastic-scout-driver
mkwebdesign/filament-watchdog-v5
renatomarinho/laravel-page-speed
zedmagdy/filament-business-hours
renatovdemoura/blade-elements-ui
devgeek/beacon-admin
benjamin-rqt/data-watcher-bundle
atriumphp/atrium
sandermuller/package-boost-laravel
sandermuller/boost-skills
redaxo/core
yusufgenc/filament-api-forge
l3aro/rating-star-for-filament
leek/filament-subtenant-scope