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

clevis/push-notifications

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Steps

  1. Installation Add the package via Composer:

    composer require clevis/push-notifications:~0.1-beta
    

    Enable the extension in config.neon:

    extensions:
        pushNotifications: Clevis\PushNotifications\DI\PushNotificationsExtension
    
  2. Configure Credentials Update config.neon with your provider credentials (e.g., GCM, APNs, or C2DM):

    pushNotifications:
        android:
            gcm:
                apiKey: "YOUR_GCM_API_KEY"
        apple:
            sandbox: true
            pem: "%appDir%/path/to/certificate.pem"
            passphrase: "YOUR_PASSPHRASE"
    
  3. First Push Inject the Notifications service and send a test message:

    use Clevis\PushNotifications\Message\iOSMessage;
    use Clevis\PushNotifications\Notifications;
    
    class PushService
    {
        public function __construct(private Notifications $sender) {}
    
        public function sendTestNotification()
        {
            $message = new iOSMessage();
            $message->setMessage("Hello, World!")
                    ->setDeviceToken("DEVICE_TOKEN_HERE");
    
            $this->sender->send($message);
        }
    }
    

Implementation Patterns

Core Workflow

  1. Message Creation Use platform-specific message classes (iOSMessage, AndroidMessage, BlackberryMessage):

    $message = new iOSMessage();
    $message->setMessage("Your notification text")
            ->setBadge(5)
            ->setSound("default")
            ->setCustomData(['key' => 'value']);
    
  2. Sending Notifications Inject Notifications and call send():

    $this->sender->send($message);
    
  3. Batch Sending Loop through device tokens and send multiple messages:

    foreach ($deviceTokens as $token) {
        $message = new iOSMessage();
        $message->setDeviceToken($token)
                ->setMessage("Custom message for $token");
        $this->sender->send($message);
    }
    
  4. Error Handling Wrap sends in try-catch to handle exceptions (e.g., invalid tokens, API failures):

    try {
        $this->sender->send($message);
    } catch (\Exception $e) {
        Log::error("Push failed: " . $e->getMessage());
    }
    

Integration Tips

  • Dependency Injection Bind the Notifications service in your DI container (Nette) for reusable access:

    $container->addService('pushSender', $this->sender);
    
  • Queueing Offload sends to a queue (e.g., Nette Queue) for async processing:

    $queue->enqueue(new PushNotificationJob($message));
    
  • Logging Log successful/failed sends for debugging:

    $this->sender->send($message, function ($success, $response) {
        if (!$success) {
            Log::error("Push failed: " . $response);
        }
    });
    
  • Environment-Specific Config Use %env() for credentials in config.neon:

    pushNotifications:
        apple:
            pem: "%env(PUSH_CERT_PATH)%"
    

Gotchas and Tips

Pitfalls

  1. Certificate Paths

    • Issue: Windows paths in pem config may break. Use forward slashes or raw strings:
      pem: "C:/path/to/cert.pem"  # or "%appDir%/path/to/cert.pem"
      
    • Fix: Set use_multi_curl: false in GCM config for Windows.
  2. Device Tokens

    • Issue: Invalid tokens cause silent failures. Validate tokens before sending:
      if (!preg_match('/^[0-9a-f]{64}$/', $deviceToken)) {
          throw new \InvalidArgumentException("Invalid token");
      }
      
  3. APNs Sandbox vs. Production

    • Issue: Forgetting to switch between sandbox: true/false may cause deliveries to fail.
    • Fix: Use environment variables to toggle:
      apple:
          sandbox: %env(PUSH_SANDBOX)%  # true/false
      
  4. Rate Limits

    • Issue: GCM/APNs throttle requests. Batch sends to avoid bans:
      // Send in chunks of 100
      array_chunk($tokens, 100, function ($chunk) {
          foreach ($chunk as $token) { /* send */ }
      });
      

Debugging

  1. Enable Verbose Logging Add a callback to inspect responses:

    $this->sender->send($message, function ($success, $response) {
        var_dump($response); // Check raw API response
    });
    
  2. Test with Sandbox Always test iOS pushes in sandbox (sandbox: true) before production.

  3. GCM Debugging Use the GCM Developer Console to check delivery status.


Extension Points

  1. Custom Message Classes Extend AbstractMessage to add platform-specific fields:

    class CustomMessage extends AbstractMessage {
        public function setCustomField($key, $value) {
            $this->customData[$key] = $value;
            return $this;
        }
    }
    
  2. Add New Providers Implement ProviderInterface for unsupported platforms (e.g., Firebase Cloud Messaging):

    class FirebaseProvider implements ProviderInterface {
        public function send(Message $message) { /* ... */ }
    }
    
  3. Override Default Behavior Bind a custom Notifications service in DI to replace the default:

    $container->addService('pushSender', new CustomNotifications($provider));
    

Tips

  • Use Environment Variables Store sensitive keys in .env and load via %env():

    pushNotifications:
        android:
            gcm:
                apiKey: "%env(GCM_API_KEY)%"
    
  • Validate Config Early Add a bootstrapping check in Bootstrap.php:

    if (!$this->config->pushNotifications->apple->pem) {
        throw new \RuntimeException("APNs certificate path not configured!");
    }
    
  • Monitor Delivery Track sent notifications in a database for analytics:

    $this->sender->send($message, function ($success, $response) {
        PushLog::create([
            'device_token' => $message->getDeviceToken(),
            'status' => $success ? 'sent' : 'failed',
            'response' => $response
        ]);
    });
    
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.
comsave/common
alecsammon/php-raml-parser
chrome-php/wrench
lendable/composer-license-checker
typhoon/reflection
mesilov/moneyphp-percentage
mike42/gfx-php
bookdown/themes
aura/view
aura/html
aura/cli
povils/phpmnd
nayjest/manipulator
omnipay/tests
psr-mock/http-message-implementation
psr-mock/http-factory-implementation
psr-mock/http-client-implementation
voku/email-check
voku/urlify
rtheunissen/guzzle-log-middleware