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

Push Notifications Laravel Package

bluetea/push-notifications

PHP library by BlueTea for sending push notifications. Provides a lightweight foundation to integrate push messaging into your application and manage notification delivery across supported providers.

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Installation:

    composer require bluetea/push-notifications
    

    (Note: Due to PHP 5.4 compatibility, ensure your project uses PHP 5.4+ or adjust your environment if needed.)

  2. Basic Initialization:

    use BlueTea\PushNotifications\PushNotification;
    
    $push = new PushNotification([
        'appId' => 'YOUR_ONESIGNAL_APP_ID',
        'authToken' => 'YOUR_ONESIGNAL_AUTH_TOKEN',
        'endpoint' => 'https://onesignal.com/api/v1/notifications' // Default
    ]);
    
  3. First Use Case: Send a simple notification to all users:

    $response = $push->send([
        'contents' => ['en' => 'Hello from Laravel!'],
        'include_player_ids' => ['player_id_1', 'player_id_2']
    ]);
    

Where to Look First

  • README.md: Basic setup and usage.
  • src/BlueTea/PushNotifications/PushNotification.php: Core class methods (e.g., send(), sendToAll()).
  • Tests: Limited but useful for edge cases (e.g., error handling).

Implementation Patterns

Common Workflows

  1. Sending Notifications:

    • Targeted Users:
      $push->send([
          'contents' => ['en' => 'Your order is shipped!'],
          'include_player_ids' => [$user->device_token],
      ]);
      
    • All Users:
      $push->sendToAll(['contents' => ['en' => 'System update available!']]);
      
    • Segments:
      $push->sendToSegment('active_users', ['contents' => ['en' => 'Welcome back!']]);
      
  2. Handling Responses:

    $response = $push->send([...]);
    if ($response->success()) {
        // Log or process success
    } else {
        Log::error('Push failed:', ['error' => $response->getError()]);
    }
    
  3. Integration with Laravel:

    • Service Provider: Bind the class in AppServiceProvider:
      $this->app->singleton('push', function ($app) {
          return new PushNotification(config('services.onesignal'));
      });
      
    • Config File (config/services.php):
      'onesignal' => [
          'appId' => env('ONESIGNAL_APP_ID'),
          'authToken' => env('ONESIGNAL_AUTH_TOKEN'),
          'endpoint' => env('ONESIGNAL_ENDPOINT', 'https://onesignal.com/api/v1/notifications'),
      ],
      
    • Facade (Optional): Create a facade for cleaner syntax:
      // app/Facades/PushNotification.php
      class PushNotification extends Facade {
          protected static function getFacadeAccessor() { return 'push'; }
      }
      
      Usage:
      PushNotification::send([...]);
      
  4. Event-Based Triggers:

    • Listen to model events (e.g., OrderShipped) and dispatch notifications:
      event(new OrderShipped($order));
      // In listener:
      PushNotification::send([...]);
      

Gotchas and Tips

Pitfalls

  1. Deprecated/Outdated:

    • No Laravel 8/9 Support: Uses PHP 5.4 syntax (e.g., array() instead of []). May require manual fixes for newer PHP/Laravel.
    • OneSignal API Changes: Endpoints/auth may break if OneSignal updates their API. Check release/v1.0.3.md for adjustments.
    • No Retry Logic: Failed requests aren’t retried by default. Implement middleware or a queue job.
  2. Error Handling:

    • Silent Failures: Always check $response->success() or getError().
    • HTTP Errors: Wrap calls in try-catch for network issues:
      try {
          $push->send([...]);
      } catch (\Exception $e) {
          Log::error('Push notification failed', ['exception' => $e]);
      }
      
  3. Configuration Quirks:

    • Hardcoded Endpoint: Default endpoint is hardcoded in the class. Override via constructor or config.
    • No Rate Limiting: OneSignal’s API may throttle requests. Add delays or use queues.

Debugging Tips

  1. Enable Logging:

    $push = new PushNotification([...], true); // Enable debug mode (if supported)
    

    (Note: Debug mode isn’t documented; inspect the class for logging hooks.)

  2. Inspect Raw Responses:

    $response = $push->send([...]);
    dd($response->getRawResponse()); // Dump OneSignal's raw JSON
    
  3. Test with Postman: Manually test OneSignal endpoints using your appId/authToken to verify issues aren’t package-specific.

Extension Points

  1. Custom Endpoints: Override the endpoint in the constructor or extend the class:

    class CustomPushNotification extends PushNotification {
        public function __construct(array $config) {
            $config['endpoint'] = 'https://custom-endpoint.com/api';
            parent::__construct($config);
        }
    }
    
  2. Add Metadata: Extend the send() payload dynamically:

    $push->send(array_merge([
        'contents' => ['en' => 'Hello'],
        'data' => ['custom_key' => 'value'], // Additional metadata
    ], $extraData));
    
  3. Queue Jobs: Offload notifications to Laravel queues:

    // In a job class:
    public function handle() {
        PushNotification::send([...]);
    }
    

    Dispatch with:

    dispatch(new SendPushNotificationJob($payload));
    
  4. Mocking for Tests: Use Laravel’s mocking to avoid real API calls:

    $mock = Mockery::mock('overload:BlueTea\PushNotifications\PushNotification');
    $mock->shouldReceive('send')->andReturn(new PushResponse(true));
    
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.
terminal42/code-quality-tools
codifyo/ts-generator-bundle
andydefer/laravel-cluster
testo/fiber
mintobit/jobqueue
a4sex/maintenance-bundle
a4sex/entity-date-update
a4sex/client-identifier
a4sex/base-utilites
a4sex/key-value-storage
a4sex/micro-status
chilldev/dependency-injection-extra
datinglibre/datinglibre-app-api
biberltd/corebundle
bricre/symfony-bundle-test
biberltd/logbundle
dominium/http-adapter-bundle
dominium/google-analytics
a4sex/auto-clean-entity
christhompsontldr/laravel-inky