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

Notifications Laravel Package

atakajlo/notifications

View on GitHub
Deep Wiki
Context7

Getting Started

First Steps

  1. Installation

    composer require atakajlo/notifications
    

    Publish the config (if available):

    php artisan vendor:publish --provider="Atakajlo\Notifications\NotificationsServiceProvider"
    
  2. Basic Setup

    • Register the service provider in config/app.php (if not auto-discovered):
      'providers' => [
          Atakajlo\Notifications\NotificationsServiceProvider::class,
      ],
      
    • Check config/notifications.php for default configurations (e.g., channels, drivers).
  3. First Use Case: Sending a Notification

    use Atakajlo\Notifications\Notification;
    use Atakajlo\Notifications\Channels\MailChannel;
    
    // Define a notification class
    class OrderShipped extends Notification
    {
        public function via($notifiable)
        {
            return [MailChannel::class];
        }
    
        public function toMail($notifiable)
        {
            return (new MailMessage)
                ->subject('Your order has shipped!')
                ->line('Thank you for your purchase.');
        }
    }
    
    // Send the notification
    $user = User::find(1);
    $user->notify(new OrderShipped());
    

Implementation Patterns

Common Workflows

  1. Channel-Specific Notifications

    • Extend Notification and define via() to specify channels (e.g., MailChannel, DatabaseChannel, SlackChannel).
    • Example for SMS (if supported):
      public function via($notifiable)
      {
          return [new SMSChannel('twilio')];
      }
      
  2. Dynamic Recipients

    • Use notify() with collections or multiple recipients:
      $users = User::where('role', 'admin')->get();
      $users->notify(new SystemUpdate());
      
  3. Queued Notifications

    • Leverage Laravel’s queue system for async delivery:
      $user->notify(new OrderShipped())->onQueue('notifications');
      
  4. Customizing Notifications

    • Override toArray(), toMail(), or other channel methods per notification type.
    • Example for a custom channel:
      public function toCustomChannel($notifiable)
      {
          return ['key' => 'value'];
      }
      
  5. Event-Based Triggers

    • Dispatch notifications from events (e.g., OrderShipped event):
      event(new OrderShipped($order));
      // In the event listener:
      $order->user->notify(new OrderShippedNotification($order));
      

Integration Tips

  • Laravel Mixins: Use traits to reuse notification logic across classes.
  • Testing: Mock channels or use Notification::fake() for unit tests:
    Notification::fake();
    $user->notify(new OrderShipped());
    Notification::assertSentTo($user, OrderShipped::class);
    
  • Localization: Pass locale to notifications for multilingual support:
    $user->notify(new OrderShipped())->locale('es');
    

Gotchas and Tips

Pitfalls

  1. Channel Configuration

    • Ensure channels (e.g., mail, database) are properly configured in config/services.php or config/notifications.php.
    • Example for Mail:
      'mail' => [
          'driver' => env('MAIL_DRIVER', 'smtp'),
          'host' => env('MAIL_HOST', 'smtp.mailgun.org'),
          // ... other SMTP settings
      ],
      
  2. Missing notifiable Interface

    • Models must implement Illuminate\Notifications\Notifiable to receive notifications.
    • Fix: Add the trait to your model:
      use Illuminate\Notifications\Notifiable;
      class User extends Authenticatable
      {
          use Notifiable;
      }
      
  3. Queue Stuck Jobs

    • If notifications aren’t delivered, check:
      • Queue worker is running (php artisan queue:work).
      • Database connection for failed_jobs table (if using database queue).
      • Logs for errors (storage/logs/laravel.log).
  4. Channel-Specific Quirks

    • Mail: Ensure from address is set in config/mail.php.
    • Database: Verify the notifications table exists (migrate if needed).
    • Third-Party (e.g., Slack): Validate API keys and webhook URLs.

Debugging

  • Log Notifications: Use Laravel’s logging to debug:
    \Log::debug('Notification sent', ['data' => $notification->toArray()]);
    
  • Inspect Failed Jobs: Check failed_jobs table or run:
    php artisan queue:failed
    
  • Channel-Specific Debugging:
    • For mail, check SMTP logs or use a local mail server (e.g., MailHog).
    • For database, inspect the notifications table directly.

Extension Points

  1. Custom Channels

    • Create a new channel by extending Illuminate\Notifications\ChannelManager or Atakajlo\Notifications\Channels\BaseChannel.
    • Example:
      namespace App\Notifications\Channels;
      use Atakajlo\Notifications\Channels\BaseChannel;
      class PushChannel extends BaseChannel
      {
          public function send($notifiable, $notification)
          {
              // Custom logic (e.g., Firebase Cloud Messaging)
          }
      }
      
  2. Notification Middleware

    • Add middleware to notifications via app/Providers/EventServiceProvider:
      protected $listen = [
          'Atakajlo\Notifications\Events\NotificationPrepared' => [
              \App\Notifications\Middleware\LogNotification::class,
          ],
      ];
      
  3. Dynamic Channel Selection

    • Use closures in via() to conditionally select channels:
      public function via($notifiable)
      {
          return $notifiable->prefers_sms ? [SMSChannel::class] : [MailChannel::class];
      }
      
  4. Batch Processing

    • For bulk notifications, use Laravel’s batch() helper or chunk processing:
      User::chunk(100, function ($users) {
          $users->each->notify(new WeeklyNewsletter());
      });
      
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