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

Notify Bundle Laravel Package

austral/notify-bundle

View on GitHub
Deep Wiki
Context7
## Getting Started

### Minimal Setup
1. **Installation**
   Add the bundle via Composer:
   ```bash
   composer require austral/notify-bundle

Register the bundle in config/bundles.php:

Austral\NotifyBundle\AustralNotifyBundle::class => ['all' => true],
  1. Publish Config Publish the default configuration:

    php artisan vendor:publish --tag="notify-bundle-config"
    

    This generates config/notify.php with Mercure and push notification settings.

  2. First Use Case: Sending a Notification Use the NotifyManager service to dispatch notifications:

    use Austral\NotifyBundle\Manager\NotifyManager;
    
    class MyController extends Controller
    {
        public function __construct(private NotifyManager $notifyManager) {}
    
        public function sendNotification()
        {
            $this->notifyManager->push(
                'user_id', // Target user ID
                'channel_name', // Notification channel (e.g., 'inbox')
                [
                    'title' => 'New Message',
                    'message' => 'You have a new message!',
                    'data' => ['url' => '/messages/123']
                ]
            );
        }
    }
    
  3. Mercure Integration Enable Mercure in config/notify.php:

    'mercure' => [
        'enabled' => true,
        'url' => env('MERCURE_URL', 'http://localhost:.3000/.well-known/mercure'),
        'public_key' => env('MERCURE_PUBLIC_KEY'),
        'private_key' => env('MERCURE_PRIVATE_KEY'),
    ],
    

    Ensure your frontend subscribes to the Mercure hub URL (e.g., http://localhost:.3000/.well-known/mercure).


Implementation Patterns

Core Workflows

  1. Push Notifications

    • Single User: Use notifyManager->push($userId, $channel, $data).
    • Broadcast to Multiple Users: Loop through user IDs or use a query builder:
      $userIds = User::where('role', 'admin')->pluck('id');
      foreach ($userIds as $userId) {
          $this->notifyManager->push($userId, 'admin-alerts', $data);
      }
      
    • Channel-Specific Logic: Extend the bundle by creating custom channels (see "Extension Points").
  2. Mercure Integration

    • Real-Time Updates: Mercure automatically broadcasts notifications to subscribed clients.
    • Topic Format: Notifications are published to topics like https://yourdomain.com/.well-known/mercure?topic=notify:user_id:channel_name.
    • Frontend Subscription: Use JavaScript to subscribe to topics:
      const eventSource = new EventSource(
          'http://localhost:.3000/.well-known/mercure?topic=notify:123:inbox'
      );
      eventSource.onmessage = (event) => {
          const data = JSON.parse(event.data);
          console.log('New notification:', data);
      };
      
  3. Config-Driven Customization

    • Push Types: Use constants like Austral\NotifyBundle\Enum\PushType::WEB or PushType::MOBILE to filter notifications.
    • Enabled Services: Toggle Mercure or other services via config/notify.php without code changes.
  4. Event-Driven Notifications

    • Listen for model events (e.g., Created, Updated) and dispatch notifications:
      use Austral\NotifyBundle\Manager\NotifyManager;
      use Illuminate\Queue\Events\JobProcessed;
      
      class MyEventListener
      {
          public function __construct(private NotifyManager $notifyManager) {}
      
          public function handle(JobProcessed $event)
          {
              $this->notifyManager->push(
                  $event->job->data['user_id'],
                  'job-complete',
                  ['job_id' => $event->job->id]
              );
          }
      }
      

Integration Tips

  • Laravel Queues: Dispatch notifications asynchronously:
    $this->notifyManager->push($userId, 'channel', $data)->onQueue('notifications');
    
  • Validation: Validate notification data before pushing:
    $validator = Validator::make($data, [
        'title' => 'required|string|max:255',
        'message' => 'required|string',
    ]);
    if ($validator->fails()) {
        throw new \InvalidArgumentException('Invalid notification data');
    }
    
  • Testing: Mock NotifyManager in tests:
    $mock = Mockery::mock(NotifyManager::class);
    $mock->shouldReceive('push')->once()->withArgs([1, 'test', ['key' => 'value']]);
    $this->app->instance(NotifyManager::class, $mock);
    

Gotchas and Tips

Pitfalls

  1. Mercure Configuration

    • Missing Keys: If MERCURE_PUBLIC_KEY or MERCURE_PRIVATE_KEY are missing, Mercure will fail silently. Enable debug mode in config/notify.php to log errors:
      'debug' => env('APP_DEBUG', false),
      
    • CORS Issues: Ensure your Mercure hub allows requests from your frontend domain. Configure CORS in Mercure’s .env:
      MERCURE_ALLOW_ORIGINS=http://localhost:3000,https://yourdomain.com
      
  2. Push Type Constants

    • Deprecation Risk: The bundle uses PushType constants (e.g., PushType::WEB). If the enum changes in future versions, update your code to use the new constants or methods.
  3. Channel Naming

    • Collision Risk: Avoid generic channel names (e.g., notifications) to prevent unintended overlaps. Use namespaced channels like user:123:messages.
  4. Database Overhead

    • Unbounded Data: If not careful, pushing large payloads to Mercure or storing notifications in a database can bloat storage. Sanitize data before pushing:
      $data = array_intersect_key($data, array_flip(['title', 'message', 'url']));
      

Debugging

  1. Log Notifications Enable logging in config/notify.php:

    'log' => [
        'enabled' => true,
        'channel' => 'single',
        'level' => 'debug',
    ],
    

    Check logs in storage/logs/laravel.log for pushed notifications.

  2. Mercure Debugging

    • Hub Logs: Check Mercure’s logs (e.g., var/log/mercure.log) for subscription/publish errors.
    • Topic Validation: Use the Mercure debug endpoint to validate topics:
      curl http://localhost:.3000/.well-known/mercure?topic=notify:123:inbox
      
  3. Frontend Debugging

    • EventSource Errors: Listen for error events on the frontend to catch Mercure connection issues:
      eventSource.onerror = (error) => {
          console.error('Mercure error:', error);
      };
      

Tips

  1. Extending the Bundle

    • Custom Channels: Create a service provider to add channel-specific logic:
      class CustomChannelProvider extends AbstractChannelProvider
      {
          public function handle($userId, $data)
          {
              // Custom logic for 'custom-channel'
              if ($data['type'] === 'urgent') {
                  $this->sendSms($userId, $data['message']);
              }
          }
      }
      
      Register it in config/notify.php:
      'channels' => [
          'custom-channel' => \App\Providers\CustomChannelProvider::class,
      ],
      
  2. Rate Limiting

    • Limit Mercure publishes to avoid overwhelming clients:
      'mercure' => [
          'rate_limit' => 10, // Max publishes per second
      ],
      
  3. Environment-Specific Config

    • Override config per environment (e.g., disable Mercure in testing):
      // config/notify.php (testing)
      'mercure' => [
          'enabled' => env('MERCURE_ENABLED', false),
      ],
      
  4. Type Safety

    • Use PHP 8.2+ attributes to enforce notification data structure:
      #[Attribute]
      class NotificationData
      {
          public function __construct(
              public string $title,
              public string $message,
              public ?string $url = null,
          ) {}
      }
      
      Validate in your controller:
      $data = new NotificationData(...);
      $this->notifyManager->push($userId, 'channel', $data);
      
  5. Fallback Mechanisms

    • Combine Mercure with email/SMS fallbacks:
      $this->notify
      
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.
cocosmos/filament-sticky-save-bar
patrickbussmann/oauth2-apple
3brs/enterprise-security-bundle
anousss007/vigilance
supportpal/eloquent-model
ardenexal/fhir-models
laravel-at/laravel-image-sanitize
romalytar/yammi-audit-log-laravel
ardenexal/fhir-validation
arshaviras/weather-widget
laravel-chronicle/core
sunchayn/nimbus
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