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

mckenziearts/laravel-notify

Lightweight Laravel package for backend-driven toast notifications. Publish config/assets, drop in a Blade component, and trigger success/error/info messages from your app. Works great with Tailwind CSS and Alpine.js for smooth UI alerts.

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Steps

  1. Installation:

    composer require mckenziearts/laravel-notify
    php artisan vendor:publish --tag=notify-config
    php artisan vendor:publish --tag=notify-assets
    
  2. Tailwind Integration (Recommended):

    • Add @source directive in resources/css/app.css:
      @source "../../vendor/mckenziearts/laravel-notify/resources/views/**/*.blade.php";
      
    • Import Alpine.js in resources/js/app.js:
      import Alpine from 'alpinejs';
      window.Alpine = Alpine;
      Alpine.start();
      
    • Include the notification component in your layout (resources/views/layouts/app.blade.php):
      <x-notify::notify />
      
    • Run npm run dev or npm run build.
  3. First Notification:

    // In a controller method
    notify()->success()->title('Success!')->send();
    return back();
    

First Use Case

Display a success toast notification after a form submission:

public function store(Request $request) {
    $validated = $request->validate([...]);
    // Save data...

    notify()->success()->title('Record saved')->send();
    return back();
}

Implementation Patterns

Core Workflow

  1. Notification Chain:

    notify()
        ->model(NotificationModel::Toast) // Optional (defaults to Toast)
        ->type(NotificationType::Success) // success, error, warning, info
        ->title('Action completed')
        ->message('Optional details')
        ->duration(3000) // Optional (default: 5000ms)
        ->send();
    
  2. Actionable Notifications:

    notify()
        ->success()
        ->title('User deleted')
        ->actions([
            NotifyAction::make()
                ->label('Undo')
                ->action(route('users.restore', $user->id)),
            NotifyAction::make()
                ->label('View')
                ->url(route('users.index'))
                ->openUrlInNewTab(),
        ])
        ->send();
    
  3. Preset Notifications:

    // In config/notify.php
    'preset-messages' => [
        'user.created' => [
            'type' => NotificationType::Success,
            'title' => 'User created',
            // ...
        ],
    ];
    
    // Usage
    notify()->preset('user.created')->send();
    

Integration Tips

  • Form Requests: Use in FormRequest classes for validation feedback:

    public function failedValidation(Validator $validator) {
        notify()->error()->title('Validation failed')->send();
        return back()->withErrors($validator);
    }
    
  • Service Layer: Create a dedicated NotificationService to centralize logic:

    class NotificationService {
        public function success(string $title, ?string $message = null) {
            notify()->success()->title($title)->message($message)->send();
        }
    }
    
  • Event Listeners: Trigger notifications on events:

    public function handle(UserCreated $event) {
        notify()->preset('user.created')->send();
    }
    
  • API Responses: Use for API responses (with @notifyJs directive in Blade):

    return response()->json(['success' => true], 200)
        ->header('X-Notify', json_encode([
            'type' => 'success',
            'title' => 'API Success',
        ]));
    

Advanced Patterns

  1. Dynamic Presets:

    notify()->preset('user.created', [
        'title' => "User {$user->name} created",
        'message' => "ID: {$user->id}"
    ])->send();
    
  2. Conditional Notifications:

    if ($user->isAdmin()) {
        notify()->info()->title('Admin action')->send();
    } else {
        notify()->success()->title('Action completed')->send();
    }
    
  3. Batch Processing:

    foreach ($users as $user) {
        notify()->preset('user.processed', [
            'title' => "Processed {$user->email}"
        ])->send();
    }
    

Gotchas and Tips

Common Pitfalls

  1. Asset Loading Issues:

    • Problem: Notifications not appearing after npm run build.
    • Fix: Ensure @notifyJs and @notifyCss directives are in the correct layout file (or Tailwind is configured to scan package views).
  2. Action Execution Failures:

    • Problem: Actions not triggering or failing silently.
    • Debug: Check browser console for errors. Ensure:
      • Routes are correct.
      • CSRF token is included (handled automatically by the package).
      • The notification model supports actions (e.g., Drake does not).
  3. Duration Overrides:

    • Problem: duration() not working as expected.
    • Fix: Verify the config value (config/notify.php) isn’t overriding your method call. Method calls take precedence.
  4. Preset Overrides:

    • Problem: Overrides not applying to preset notifications.
    • Fix: Pass overrides as an associative array:
      notify()->preset('user.created', ['title' => 'New title'])->send();
      

Debugging Tips

  1. Inspect the Queue:

    • Use dd(\Mckenziearts\Notify\Facades\Notify::queue()) to see pending notifications before send().
  2. Check the View:

    • Inspect the rendered HTML for <x-notify::notify /> to ensure it’s loaded.
  3. Alpine.js Conflicts:

    • If Alpine.js isn’t working, ensure:
      • It’s properly imported in app.js.
      • No duplicate Alpine instances are loaded.
  4. Tailwind Scanning:

    • If styles aren’t applied, verify:
      • @source directive is in app.css.
      • Tailwind is configured to scan resources/views and vendor files.

Extension Points

  1. Custom Notification Models:

    • Extend the NotificationModel enum or create a new model class by implementing Mckenziearts\Notify\Contracts\NotificationModel.
  2. Custom Actions:

    • Extend NotifyAction to add custom behavior:
      class CustomAction extends NotifyAction {
          public function customMethod() { ... }
      }
      
  3. Global Middleware:

    • Add middleware to auto-notify on specific routes:
      public function handle($request, Closure $next) {
          notify()->info()->title('Entering admin area')->send();
          return $next($request);
      }
      
  4. Testing:

    • Use the facade directly in tests:
      $this->expectsNotifications(1)
          ->notify()
          ->success()
          ->title('Test')
          ->send();
      

Configuration Quirks

  1. Default Timeout:

    • Set in config/notify.php:
      'timeout' => env('NOTIFY_TIMEOUT', 5000), // Default: 5000ms
      
  2. Asset Paths:

    • Pre-compiled assets are published to public/vendor/mckenziearts/laravel-notify/dist/. Clear cached views if styles break after updates:
      php artisan view:clear
      
  3. Alpine.js Version:

    • The package uses Alpine.js v3. Ensure your project’s Alpine.js version is compatible (check package.json).
  4. Laravel Version:

    • Tested up to Laravel 13. For older versions, check the changelog for compatibility notes.

Performance Tips

  1. Batch Notifications:

    • For bulk operations, queue notifications to avoid rendering delays:
      foreach ($items as $item) {
          notify()->preset('item.processed')->send();
      }
      
  2. Disable Auto-Send:

    • Use queue() to defer sending until later:
      notify()->success()->title('Pending')->queue();
      // Later...
      \Mckenziearts\Notify\Facades\Notify::sendQueued();
      
  3. Minimize Actions:

    • Actions trigger HTTP requests. Use sparingly for complex workflows to avoid performance overhead.
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.
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
renatovdemoura/blade-elements-ui
devgeek/beacon-admin
benjamin-rqt/data-watcher-bundle
atriumphp/atrium
sandermuller/package-boost-laravel
sandermuller/boost-skills
redaxo/core
yusufgenc/filament-api-forge
l3aro/rating-star-for-filament
leek/filament-subtenant-scope
anil/file-picker
broqit/fields-ai