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 Symfony Bundle Laravel Package

authbucket/push-symfony-bundle

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup in Laravel

Since this is a Symfony bundle, Laravel integration requires Symfony Bridge or Laravel Symfony Integration (e.g., spatie/laravel-symfony). Start by:

  1. Install Dependencies

    composer require authbucket/push-symfony-bundle
    composer require spatie/laravel-symfony  # Bridge for Laravel
    
  2. Register the Bundle In config/app.php, add the bundle to config['extra.bundles'] under SymfonyBridge::getBundles():

    'extra' => [
        'bundles' => [
            SymfonyBridge::getBundles([
                AuthBucket\PushBundle\AuthBucketPushBundle::class,
            ]),
        ],
    ],
    
  3. Configure Services Publish the bundle config:

    php artisan vendor:publish --provider="AuthBucket\PushBundle\AuthBucketPushBundle"
    

    Update config/push.php with your APNs/GCM credentials (e.g., API keys, certificates).

  4. First Push Notification Use the service container to send a test notification:

    use AuthBucket\PushBundle\Service\PushService;
    
    $pushService = app(PushService::class);
    $pushService->sendPush(
        'device_token_here', // User's device token
        'Hello from Laravel!', // Alert message
        ['custom_key' => 'value'] // Optional payload
    );
    

Implementation Patterns

Core Workflows

  1. Device Management

    • Store device tokens in a database (e.g., devices table with user_id, device_token, platform).
    • Use Laravel’s Eloquent to fetch tokens:
      $tokens = Device::where('user_id', auth()->id())->pluck('device_token');
      
  2. Bulk Notifications

    • Loop through tokens and send pushes:
      foreach ($tokens as $token) {
          $pushService->sendPush($token, 'Your message');
      }
      
  3. Event-Driven Triggers

    • Hook into Laravel events (e.g., auth.login) to send welcome pushes:
      use Illuminate\Support\Facades\Event;
      
      Event::listen('auth.login', function ($user) {
          $pushService->sendPush($user->device->token, 'Welcome back!');
      });
      
  4. Platform-Specific Logic

    • Use the bundle’s PushService to target APNs (iOS) or GCM (Android):
      $pushService->setPlatform('apns'); // or 'gcm'
      

Integration Tips

  • Laravel Queues: Wrap sendPush() in a job to avoid timeouts:
    use AuthBucket\PushBundle\Jobs\SendPushJob;
    
    SendPushJob::dispatch($token, 'Message')->onQueue('push');
    
  • Service Container Binding: Extend the PushService for custom logic:
    $app->bind(PushService::class, function ($app) {
        $service = new PushService($app['config']['push']);
        $service->setLogger($app['log']); // Inject Laravel’s logger
        return $service;
    });
    

Gotchas and Tips

Pitfalls

  1. Symfony vs. Laravel Compatibility

    • The bundle assumes Symfony’s ContainerInterface. Use spatie/laravel-symfony to bridge services.
    • Fix: Override the service provider to adapt to Laravel’s container:
      $app->singleton(PushService::class, function ($app) {
          return new PushService($app['config']['push'], $app['log']);
      });
      
  2. Database Schema Mismatch

    • The bundle expects a device table. Define a migration:
      php artisan make:migration create_devices_table
      
      Schema::create('devices', function (Blueprint $table) {
          $table->id();
          $table->foreignId('user_id')->constrained();
          $table->string('device_token')->unique();
          $table->string('platform'); // 'apns' or 'gcm'
          $table->timestamps();
      });
      
  3. Certificate Handling (APNs)

    • APNs requires .pem files. Store them securely (e.g., Laravel’s storage/app) and reference in config/push.php:
      'apns' => [
          'certificate_path' => storage_path('app/certificates/auth_bucket.pem'),
          'passphrase' => env('APNS_PASSPHRASE'),
      ],
      
  4. Rate Limiting

    • APNs/GCM have strict rate limits. Use Laravel’s throttle middleware or queue delays:
      SendPushJob::dispatch($token, 'Message')->delay(now()->addMinutes(1));
      

Debugging Tips

  • Enable Logging: Configure Monolog in config/push.php:
    'logging' => [
        'enabled' => true,
        'channel' => 'push', // Laravel’s log channel
    ],
    
  • Test with Sandbox: Use APNs sandbox for development:
    $pushService->setEnvironment('sandbox'); // APNs
    $pushService->setEnvironment('development'); // GCM
    
  • Payload Validation: Validate JSON payloads before sending:
    $payload = json_encode(['alert' => 'Test'], JSON_UNESCAPED_UNICODE);
    if (json_last_error() !== JSON_ERROR_NONE) {
        throw new \RuntimeException('Invalid payload');
    }
    

Extension Points

  1. Custom Payloads Extend the PushService to add metadata:

    class CustomPushService extends PushService {
        public function sendCustomPush($token, $message, array $metadata = []) {
            $payload = array_merge([
                'alert' => $message,
                'metadata' => $metadata,
            ]);
            return $this->sendPush($token, json_encode($payload));
        }
    }
    
  2. Webhook Integration Use Laravel’s Http client to handle push responses:

    $response = Http::post('https://api.gcm.googleapis.com/...', [
        'headers' => ['Authorization' => 'key=YOUR_KEY'],
        'json' => ['registration_ids' => [$token], 'data' => ['message' => 'Hello']],
    ]);
    
  3. Analytics Track push success/failure in a push_events table:

    event(new PushSent($token, $message, $response->successful()));
    
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