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 Bell Laravel Package

caiquebispo/notification-bell

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Steps to First Notification

  1. Install the package:

    composer require caiquebispo/notification-bell
    php artisan vendor:publish --tag="notification-bell-config"
    php artisan migrate
    
  2. Add the trait to your User model:

    use CaiqueBispo\NotificationBell\Traits\HasNotifications;
    
    class User extends Authenticatable
    {
        use HasNotifications;
    }
    
  3. Include the Livewire component in your layout (e.g., resources/views/layouts/app.blade.php):

    @auth
        <livewire:notification-bell />
    @endauth
    
  4. Trigger your first notification (e.g., in a controller or job):

    auth()->user()->success(
        $targetUserId, // Can be the same as auth()->id() for self-notifications
        'Welcome!',
        'You have successfully registered.'
    );
    
  5. Start the queue worker (if using queued notifications):

    php artisan queue:work
    

First Use Case: User Registration Confirmation

// In your registration controller
public function register(Request $request)
{
    $user = User::create($request->validated());

    // Send a success notification to the newly registered user
    $user->success(
        $user->id,
        'Registration Complete',
        'Your account has been created successfully. Welcome!'
    );

    return redirect('/dashboard');
}

Implementation Patterns

Core Workflow: Notification Lifecycle

  1. Trigger:

    • Use NotificationHelper or the HasNotifications trait in your controllers, jobs, or events.
    • Example:
      // Using the helper
      NotificationHelper::info($userId, 'System Update', 'New features are available.');
      
      // Using the trait (directly on the User model)
      auth()->user()->warning($userId, 'Low Storage', 'Your storage is running low.');
      
  2. Queue Handling:

    • Notifications are queued by default. Ensure your queue worker is running:
      php artisan queue:work --daemon
      
    • For testing, use php artisan queue:work without --daemon to see notifications process in real-time.
  3. Display:

    • The Livewire component (notification-bell) automatically renders unread notifications in a dropdown.
    • Customize the dropdown position or styling via Tailwind classes in the published views.
  4. User Interaction:

    • Users can mark notifications as read by clicking them or using the "Mark All as Read" button.
    • Admins can manage notifications via the built-in admin panel at /notifications (configurable).

Integration Patterns

1. Event-Driven Notifications

Listen to Laravel events and trigger notifications:

// In EventServiceProvider
protected $listen = [
    'order.created' => [
        function (OrderCreated $event) {
            NotificationHelper::success(
                $event->order->user_id,
                'Order Created',
                'Your order #' . $event->order->id . ' is confirmed.',
                ['order_id' => $event->order->id],
                route('orders.show', $event->order)
            );
        },
    ],
];

2. Job-Based Notifications

Delay notifications using Laravel jobs (e.g., for email digests or batch processing):

// Create a job
php artisan make:job SendDelayedNotification

// In the job
public function handle()
{
    NotificationHelper::info(
        $this->userId,
        'Scheduled Reminder',
        'This is a delayed notification.'
    );
}

// Dispatch the job
SendDelayedNotification::dispatch($userId)->delay(now()->addHours(1));

3. Dynamic Notification Content

Pass context data (e.g., URLs, IDs) to notifications for actionable links:

auth()->user()->success(
    $userId,
    'Payment Received',
    'Your payment of $' . $amount . ' was processed.',
    ['payment_id' => $payment->id], // Metadata
    route('payments.show', $payment) // Action URL
);

The dropdown will render a clickable link to the payment page.

4. Bulk Notifications

Send notifications to multiple users via Artisan or code:

// Via Artisan
php artisan notifications:send-bulk "System Maintenance" "The system will be down for maintenance." --users=1,2,3 --type=warning

// Via code
$admin = User::where('role', 'admin')->get();
NotificationHelper::create(
    $admin->pluck('id')->toArray(),
    'Admin Alert',
    'A critical issue has been detected.'
);

5. Customizing the Dropdown

Publish the views and override the Livewire component:

php artisan vendor:publish --tag="notification-bell-views"

Edit resources/views/vendor/notification-bell/notification-bell.blade.php to add custom buttons or fields.


Advanced Patterns

1. Real-Time Polling

Enable polling for instant updates (e.g., for collaborative apps):

// In config/notifications.php
'polling' => [
    'enabled' => true,
    'interval' => '5s', // Poll every 5 seconds
],

The Livewire component will automatically refresh unread counts.

2. Broadcasting Notifications

Use Laravel Echo/Pusher for real-time updates (requires broadcasting setup):

// In config/notifications.php
'broadcasting' => [
    'enabled' => true,
    'channel' => 'notifications.{user_id}',
    'event' => 'NotificationCreated',
],

Trigger broadcasts in your notification logic:

broadcast(new NotificationCreated($notification))->toOthers();

3. Notification Sounds

Enable browser sounds for alerts (note: requires user interaction first):

// In config/notifications.php
'features' => [
    'sound' => [
        'enabled' => true,
        'volume' => 0.7,
    ],
],

4. Dark Mode Adaptation

The package auto-detects dark mode if your layout uses Tailwind’s dark classes:

<html class="dark">

No additional configuration is needed.


Gotchas and Tips

Pitfalls

  1. Queue Worker Requirement:

    • Notifications are queued by default. Forgetting to run php artisan queue:work will result in silent failures.
    • Fix: Use php artisan queue:work --daemon in production or test with sync driver in .env:
      QUEUE_CONNECTION=sync
      
  2. User Model Mismatch:

    • The package assumes your user model uses name for display. If your model uses nome (e.g., Brazilian systems), configure the column mapping:
      // In config/notifications.php
      'user_columns' => [
          'name' => 'nome',
      ],
      
  3. Livewire Scripts Missing:

    • The Livewire component requires @livewireScripts in your layout. Missing this will break the dropdown.
    • Fix: Ensure your layout includes:
      @livewireScripts
      
  4. Alpine.js Dependency:

    • The package uses Alpine.js for interactivity. If you’re not using Alpine elsewhere, include it in your layout:
      <script defer src="https://unpkg.com/alpinejs@3.x.x/dist/cdn.min.js"></script>
      
  5. Dark Mode Conflicts:

    • If your app has custom dark mode logic, ensure Tailwind’s dark classes are applied to the root <html> element. The package relies on this for styling.
  6. Admin Panel Access:

    • The admin panel routes are protected by the middleware defined in config/notifications.php. Ensure your auth middleware is correctly configured.

Debugging Tips

  1. Check Queue Jobs:

    • Monitor queued notifications with:
      php artisan queue:failed
      
    • Retry failed jobs:
      php artisan queue:retry all
      
  2. Log Notifications:

    • Add logging to debug notification creation:
      \Log::info('Notification triggered', [
          'user_id' => $userId,
          'title' => $title,
          'message' => $message,
      ]);
      
  3. Inspect Livewire State:

    • Use Livewire’s wire:debug to inspect the component’s state:
      @livewire('notification-bell', key('notification-bell'))
      
    • Check the network tab for Livewire updates (look for wire:init and wire:poll).
  4. Database Issues:

    • Verify the notifications table exists and has the correct structure. Run:
      php artisan migrate:fresh --seed
      
      if migrations failed.
  5. Permission Denied:

    • If notifications aren’t appearing, check:
      • The user has the HasNotifications trait.
      • The user is authenticated (the component is wrapped in @auth).
      • The queue worker is
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.
nexmo/api-specification
capell-app/block-library
axium/identity
cetria/laravel-dummy-models
cetria/reflection-helper
agropredict/sso-auth-bundle
evolvestudio/spam-protection
datacore/hub-sdk
develia/commons
cuci/prototurk-sdk
cuci/prototurk-sdk-symfony
develia/geo-bundle
dreamzy/livewire-charts
touchestate-sdk/php-sdk
ecotone/kafka
22h/doctrine-garbage-collection-bundle
agtp/agtp-php
agtp/mod-php
splash/sonata-admin
splash/metadata