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

Notification Bundle Laravel Package

bkstg/notification-bundle

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Installation

    composer require bkstg/notification-bundle
    

    Add to config/app.php under providers:

    Bkstg\NotificationBundle\Providers\NotificationServiceProvider::class,
    

    Publish the config:

    php artisan vendor:publish --provider="Bkstg\NotificationBundle\Providers\NotificationServiceProvider" --tag="config"
    
  2. First Use Case: Sending a Notification Define a notification class:

    namespace App\Notifications;
    
    use Bkstg\NotificationBundle\Contracts\Notification;
    use Illuminate\Bus\Queueable;
    use Illuminate\Notifications\Notification as BaseNotification;
    
    class OrderPlaced implements Notification
    {
        use Queueable;
    
        public function toArray()
        {
            return [
                'message' => 'Your order has been placed!',
                'order_id' => 12345,
            ];
        }
    }
    

    Trigger it via a model or event:

    use App\Notifications\OrderPlaced;
    
    $user->notify(new OrderPlaced());
    
  3. Key Config File Check config/notification.php for:

    • Default channels (e.g., mail, database, broadcast).
    • Channel-specific configurations (e.g., SMTP settings for mail).

Implementation Patterns

Core Workflows

  1. Channel-Specific Notifications Extend the bundle’s Notification contract to support custom channels:

    namespace App\Notifications;
    
    use Bkstg\NotificationBundle\Contracts\Notification;
    use Bkstg\NotificationBundle\Channels\SlackChannel;
    
    class SlackAlert implements Notification
    {
        public function via($notifiable)
        {
            return [SlackChannel::class];
        }
    
        public function toSlack($notifiable)
        {
            return [
                'text' => 'Alert: Server load high!',
                'username' => 'System Monitor',
            ];
        }
    }
    
  2. Event-Driven Notifications Attach notifications to Laravel events in EventServiceProvider:

    protected $listen = [
        'order.placed' => [
            'App\Listeners\NotifyOrderPlaced',
        ],
    ];
    

    Listener example:

    public function handle(OrderPlacedEvent $event)
    {
        $event->user->notify(new OrderPlaced());
    }
    
  3. Dynamic Channel Routing Use the routeNotificationFor method in User model to dynamically assign channels:

    public function routeNotificationFor($notification, $channel)
    {
        if ($channel === 'slack') {
            return $this->slack_webhook_url;
        }
        return $this->email;
    }
    
  4. Batch Processing Queue notifications for efficiency:

    $users = User::where('prefers_email', true)->get();
    foreach ($users as $user) {
        $user->notify(new Newsletter())->onQueue('notifications');
    }
    

Integration Tips

  • Laravel Mix/Inertia.js: Use the database channel to sync notifications with frontend:
    // Inertia.js
    const notifications = await axios.get('/api/notifications');
    
  • Testing: Mock channels in PHPUnit:
    $this->fake(SlackChannel::class);
    $user->notify(new SlackAlert());
    $this->assertCount(1, SlackChannel::assertSent());
    

Gotchas and Tips

Pitfalls

  1. Channel Registration

    • Issue: Forgetting to register custom channels in config/notification.php under channels.
    • Fix: Add your channel class path and config:
      'channels' => [
          'slack' => [
              'driver' => 'slack',
              'url' => env('SLACK_WEBHOOK_URL'),
          ],
      ],
      
  2. Missing via() Method

    • Issue: Notifications fail silently if via() is omitted.
    • Fix: Always define via() to specify channels:
      public function via($notifiable)
      {
          return ['mail', 'database'];
      }
      
  3. Queue Stuck Jobs

    • Issue: Notifications stuck in the queue due to misconfigured drivers (e.g., Redis not running).
    • Fix: Monitor queues with php artisan queue:work --queue=notifications and check failed_jobs table.
  4. Overriding Default Notifications

    • Issue: Custom notifications not overriding bundle defaults.
    • Fix: Ensure your notification class implements Bkstg\NotificationBundle\Contracts\Notification and is autoloaded.

Debugging

  • Log Channel Output: Enable debug mode in config/notification.php:

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

    Logs will appear in storage/logs/laravel.log.

  • Check Failed Jobs: Run:

    php artisan queue:failed-table
    php artisan queue:retry <job-id>
    

Extension Points

  1. Custom Channels Create a new channel by extending Bkstg\NotificationBundle\Channels\Channel:

    namespace App\Channels;
    
    use Bkstg\NotificationBundle\Channels\Channel;
    
    class CustomChannel extends Channel
    {
        public function send($notifiable, array $data)
        {
            // Custom logic (e.g., HTTP request to a service)
        }
    }
    
  2. Middleware for Notifications Add middleware to filter notifications:

    namespace App\Notifications\Middleware;
    
    use Closure;
    
    class PreventWeekendNotifications
    {
        public function handle($notifiable, Closure $next)
        {
            if (now()->dayOfWeek === \Carbon\Carbon::SATURDAY ||
                now()->dayOfWeek === \Carbon\Carbon::SUNDAY) {
                return false;
            }
            return $next($notifiable);
        }
    }
    

    Register in config/notification.php:

    'middleware' => [
        \App\Notifications\Middleware\PreventWeekendNotifications::class,
    ],
    
  3. Notification Templates Use Blade templates for dynamic content:

    public function toMail($notifiable)
    {
        return (new MailMessage)
            ->subject('Welcome!')
            ->markdown('emails.notifications.welcome', ['user' => $notifiable]);
    }
    
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.
emuniq/filament-browser-notifications
syriable/filament-translator
hungnm28/livewire-form
wenprise/eloquent
crudly/encrypted
fadion/bouncy
cuci/prototurk-sdk
gos/pubsub-router-bundle
cuci/prototurk-sdk-symfony
clementtalleu/easyadmin-markdown-bundle
codeflextech/permission-manager
karnoweb/livewire-datepicker
sayedenam/sayed-dashboard
milito/query-filter
apiboxsym/user-bundle
apiboxsym/health-check-bundle
jayeshmepani/jpl-moshier-ephemeris-php
elnasnato/laraliveui
labrodev/rest-sdk
sampaui/sampaui