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

Laravel Notification Laravel Package

shiftechafrica/laravel-notification

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Installation

    composer require shiftechafrica/laravel-notification
    php artisan vendor:publish --provider="ShiftechAfrica\Notification\NotificationServiceProvider"
    
    • Publishes the migration and config files to database/migrations/ and config/notification.php.
  2. Run Migrations

    php artisan migrate
    
    • Creates the notifications table for storing system notifications.
  3. First Use Case: Sending a Notification

    use ShiftechAfrica\Notification\Facades\Notification;
    
    // Send a notification to a user
    Notification::send(
        userId: 1, // Target user ID
        title: 'Account Update Required',
        message: 'Your account details need verification.',
        type: 'info', // 'info', 'warning', 'error', 'success'
        data: ['key' => 'value'] // Optional additional data
    );
    
  4. Displaying Notifications

    • Use the provided Blade directive @notifications in your layout:
      @notifications
      @foreach($notifications as $notification)
          <div class="alert alert-{{ $notification->type }}">
              <strong>{{ $notification->title }}</strong>
              <p>{{ $notification->message }}</p>
              @if($notification->data)
                  <pre>{{ json_encode($notification->data) }}</pre>
              @endif
          </div>
      @endforeach
      @endnotifications
      

Implementation Patterns

Core Workflows

1. Sending Notifications

  • Basic Usage

    Notification::send($userId, $title, $message, $type, $data = []);
    
    • $type: Must be one of ['info', 'warning', 'error', 'success'].
    • $data: Serialized as JSON in the database.
  • Bulk Notifications

    Notification::sendToUsers(
        userIds: [1, 2, 3],
        title: 'System Alert',
        message: 'Maintenance scheduled tomorrow.',
        type: 'warning'
    );
    
  • Conditional Notifications

    if ($user->hasUnreadNotifications()) {
        Notification::send($user->id, 'New Message', 'You have 3 unread messages.', 'info');
    }
    

2. Reading/Marking Notifications

  • Mark as Read
    Notification::markAsRead($userId, $notificationId);
    
  • Delete Notification
    Notification::delete($userId, $notificationId);
    
  • Bulk Actions
    Notification::markAllAsRead($userId); // Marks all notifications for a user as read
    

3. Querying Notifications

  • Get Unread Notifications
    $unread = Notification::getUnread($userId);
    
  • Get All Notifications (Paginated)
    $notifications = Notification::getAll($userId, 10); // Limit 10 per page
    
  • Filter by Type
    $errors = Notification::getByType($userId, 'error');
    

4. Customizing Notifications

  • Extend Notification Model Override the ShiftechAfrica\Notification\Models\Notification model in app/Models/Notification.php:

    namespace App\Models;
    
    use ShiftechAfrica\Notification\Models\Notification as BaseNotification;
    
    class Notification extends BaseNotification {
        protected $casts = [
            'data' => 'array', // Auto-cast data to array
        ];
    }
    
  • Custom Views Publish the views and override them in resources/views/vendor/notification/:

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

Integration Tips

1. Laravel Events

Trigger notifications from Laravel events:

use ShiftechAfrica\Notification\Facades\Notification;

class UserRegistered implements ShouldBroadcast {
    public function broadcast(ShouldBroadcast $event) {
        Notification::send(
            $event->user->id,
            'Welcome!',
            'Your account has been created.',
            'success'
        );
    }
}

2. Middleware for Notification Checks

Add middleware to check for unread notifications:

namespace App\Http\Middleware;

use Closure;
use ShiftechAfrica\Notification\Facades\Notification;

class CheckNotifications {
    public function handle($request, Closure $next) {
        if (auth()->check() && Notification::hasUnread(auth()->id())) {
            // Redirect or show a badge
        }
        return $next($request);
    }
}

3. API Responses

Return notifications in API responses:

return response()->json([
    'data' => $user,
    'unread_notifications' => Notification::getUnread($user->id),
]);

4. Real-Time Updates (Laravel Echo)

Use Laravel Echo to update notifications in real-time:

Echo.channel('user.notifications')
    .listen('NotificationSent', (e) => {
        // Update UI dynamically
    });
  • Requires broadcasting notifications via Laravel Echo (extend the package or use a queue).

Gotchas and Tips

Pitfalls

  1. Type Validation

    • The $type parameter must be one of ['info', 'warning', 'error', 'success']. Passing invalid types will throw an exception.
    • Fix: Validate input before calling Notification::send():
      $validTypes = ['info', 'warning', 'error', 'success'];
      if (!in_array($type, $validTypes)) {
          throw new \InvalidArgumentException("Invalid notification type.");
      }
      
  2. Data Serialization

    • The $data field is stored as JSON in the database. Ensure your data is JSON-serializable (no resources or non-serializable objects).
    • Fix: Use json_encode() or cast the field in your model:
      protected $casts = ['data' => 'array'];
      
  3. User Existence

    • The package does not validate if the $userId exists. Passing a non-existent user ID will create a notification but may cause issues elsewhere.
    • Fix: Validate the user exists before sending:
      if (!User::find($userId)) {
          throw new \InvalidArgumentException("User does not exist.");
      }
      
  4. Migration Conflicts

    • If you modify the notifications table manually, future migrations may fail. Always extend migrations via:
      php artisan make:migration extend_notifications_table --table=notifications
      

Debugging Tips

  1. Log Failed Notifications Add logging to track issues:

    Notification::send($userId, $title, $message, $type, $data);
    // Log the call for debugging
    \Log::info('Notification sent', [
        'user_id' => $userId,
        'title' => $title,
        'type' => $type,
    ]);
    
  2. Check Database Directly Verify notifications are stored correctly:

    SELECT * FROM notifications WHERE user_id = 1;
    
  3. Disable Queue for Testing Temporarily disable queues to test notifications immediately:

    Notification::setQueue(false); // Disables queue usage
    

Extension Points

  1. Custom Notification Channels Extend the package to support additional channels (e.g., SMS, email):

    // app/Providers/NotificationServiceProvider.php
    public function boot() {
        Notification::extend('sms', function ($app) {
            return new class {
                public function send($userId, $message) {
                    // Logic to send SMS
                }
            };
        });
    }
    
    • Use via:
      Notification::channel('sms')->send($userId, 'Your code: 1234');
      
  2. Notification Policies Add policies to control who can send/notifications:

    use ShiftechAfrica\Notification\Contracts\NotificationPolicy;
    
    class AdminNotificationPolicy implements NotificationPolicy {
        public function canSend($user, $notification) {
            return $user->isAdmin();
        }
    }
    
    • Register in config/notification.php:
      'policies' => [
          'admin' => \App\Policies\AdminNotificationPolicy::class,
      ],
      
    • Apply to a notification:
      Notification::send($userId, 'Alert', 'Message.', 'warning', [], 'admin');
      
  3. Custom Storage Override the storage engine (e.g., Redis, DynamoDB):

    Notification::setStorage(function () {
        return new \App\Services\RedisNotification
    
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.
milito/query-filter
apiboxsym/user-bundle
apiboxsym/health-check-bundle
jayeshmepani/jpl-moshier-ephemeris-php
elnasnato/laraliveui
labrodev/rest-sdk
sampaui/sampaui
babelqueue/php-sdk
facebook/capi-param-builder-php
babelqueue/symfony
hamzi/corewatch
minionfactory/raw-hydrator
hexters/coinpayment
rjcodes/rjcms
act-training/laravel-permissions-manager
alimarchal/laravel-chart-of-accounts
babenkoivan/elastic-scout-driver
mkwebdesign/filament-watchdog-v5
renatomarinho/laravel-page-speed
zedmagdy/filament-business-hours