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

Filament Alerts Laravel Package

tomatophp/filament-alerts

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Installation:

    composer require tomatophp/filament-alerts
    

    Publish the config file:

    php artisan vendor:publish --provider="TomatoPHP\FilamentAlerts\FilamentAlertsServiceProvider" --tag="filament-alerts-config"
    
  2. Configure Channels: Edit config/filament-alerts.php to define your notification channels (e.g., mail, database, fcm, filament). Example:

    'channels' => [
        'mail' => [
            'enabled' => true,
            'from' => 'no-reply@example.com',
        ],
        'fcm' => [
            'enabled' => true,
            'api_key' => env('FCM_API_KEY'),
        ],
    ],
    
  3. First Use Case: Send a notification via Filament’s native UI:

    use TomatoPHP\FilamentAlerts\Facades\FilamentAlerts;
    
    FilamentAlerts::send(
        user: $user,
        template: 'welcome', // Matches a template in `resources/views/vendor/filament-alerts/`
        data: ['name' => $user->name]
    );
    
  4. Define a Template: Create a Blade template at resources/views/vendor/filament-alerts/welcome.blade.php:

    <h1>Welcome, {{ $data['name'] }}!</h1>
    <p>You’ve successfully registered.</p>
    

Implementation Patterns

Core Workflows

  1. Template-Based Notifications:

    • Store reusable templates in resources/views/vendor/filament-alerts/ (e.g., order_confirmation.blade.php).
    • Pass dynamic data via the data array:
      FilamentAlerts::send($user, 'order_confirmation', ['order_id' => 123]);
      
  2. Multi-Channel Dispatch:

    • Send to all enabled channels by default:
      FilamentAlerts::send($user, 'template_name');
      
    • Target specific channels:
      FilamentAlerts::send($user, 'template_name', [], ['channels' => ['mail', 'fcm']]);
      
  3. Filament UI Integration:

    • Use the filament-alerts:send command in Filament actions/resources:
      use TomatoPHP\FilamentAlerts\Actions\SendAlertAction;
      
      public static function getActions(): array
      {
          return [
              SendAlertAction::make('Notify User')
                  ->template('welcome')
                  ->data(['name' => 'John']),
          ];
      }
      
  4. FCM (Firebase) Notifications:

    • Register a service worker in your frontend (see FCM docs).
    • Configure the fcm channel in filament-alerts.php:
      'fcm' => [
          'enabled' => true,
          'api_key' => env('FCM_SERVER_KEY'),
          'topic' => 'user_updates', // Optional: broadcast to a topic
      ],
      
  5. Macros for Custom Logic: Extend Filament’s notification service with macros:

    use TomatoPHP\FilamentAlerts\FilamentAlerts;
    
    FilamentAlerts::extend(function ($notifier) {
        $notifier->macro('urgent', function ($user, $template, $data = []) {
            return $notifier->send($user, $template, array_merge($data, ['urgent' => true]));
        });
    });
    
    // Usage:
    FilamentAlerts::urgent($user, 'alert', ['message' => 'Critical update!']);
    

Integration Tips

  • Laravel Notifications: Leverage existing Laravel notification classes for complex logic, then pass them to FilamentAlerts:

    $notification = (new OrderShipped($order))->via(['mail']);
    FilamentAlerts::send($user, 'order_shipped', [], ['notification' => $notification]);
    
  • Queue Delayed Notifications: Use Laravel queues to delay notifications:

    FilamentAlerts::later(now()->addHours(1), function () use ($user) {
        FilamentAlerts::send($user, 'reminder', ['task' => 'Complete profile']);
    });
    
  • Dynamic Templates: Fetch templates dynamically from a database or API:

    $templateContent = Cache::get("template_{$templateName}");
    FilamentAlerts::send($user, null, [], ['content' => $templateContent]);
    
  • Testing: Mock the FilamentAlerts facade in tests:

    FilamentAlerts::shouldReceive('send')->once()->with($user, 'template', ['data']);
    

Gotchas and Tips

Pitfalls

  1. Template Paths:

    • Templates must be placed in resources/views/vendor/filament-alerts/ or they won’t be found.
    • Debug missing templates with:
      php artisan view:clear
      
  2. FCM Configuration:

    • Ensure your Firebase project has the Cloud Messaging API enabled.
    • The service-worker.js must be registered in your frontend (check browser console for errors).
    • Legacy Key Issue: If using FCM_SERVER_KEY, ensure it’s a Server Key (not a Legacy Key) in Firebase Console.
  3. Channel Priority:

    • Notifications sent via FilamentAlerts override Filament’s native notifications if both are configured for the same event.
    • Explicitly disable Filament’s native notifications if conflicts arise:
      'filament' => [
          'enabled' => false,
      ],
      
  4. Data Binding:

    • Blade templates only receive the data array passed to send(). Avoid relying on global variables or session data.
    • Use array_merge to combine default and dynamic data:
      FilamentAlerts::send($user, 'template', ['default' => 'value'], ['data' => ['override' => 'value']]);
      
  5. Rate Limiting:

    • FCM has message limits. Large payloads may fail silently.
    • Log FCM responses to debug:
      'fcm' => [
          'enabled' => true,
          'log_responses' => true, // Add this to config
      ],
      

Debugging

  • Check Logs: Enable debug mode in filament-alerts.php:

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

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

  • FCM Debugging: Use the FCM DebugView to inspect sent messages.

  • Template Errors: Wrap template rendering in a try-catch to avoid crashes:

    try {
        FilamentAlerts::send($user, 'template');
    } catch (\Exception $e) {
        Log::error("Template error: " . $e->getMessage());
        // Fallback to a plain text notification
        $user->notify(new PlainTextNotification("Fallback message"));
    }
    

Extension Points

  1. Custom Channels: Extend the TomatoPHP\FilamentAlerts\Channels\Channel class to add new channels (e.g., Slack, SMS):

    namespace App\Notifications\Channels;
    
    use TomatoPHP\FilamentAlerts\Channels\Channel;
    
    class SlackChannel extends Channel
    {
        public function send($notifiable, $template, $data)
        {
            // Custom logic to send to Slack
        }
    }
    

    Register it in config/filament-alerts.php:

    'channels' => [
        'slack' => [
            'enabled' => true,
            'class' => \App\Notifications\Channels\SlackChannel::class,
        ],
    ],
    
  2. Template Preprocessing: Add a macro to preprocess template data:

    FilamentAlerts::extend(function ($notifier) {
        $notifier->macro('preprocess', function ($user, $template, $data = []) {
            $data['processed_at'] = now()->format('Y-m-d H:i');
            return $notifier->send($user, $template, $data);
        });
    });
    
  3. Event Listeners: Trigger notifications from Laravel events:

    use TomatoPHP\FilamentAlerts\Facades\FilamentAlerts;
    
    event(new UserRegistered($user));
    FilamentAlerts::send($user, 'welcome');
    
  4. Filament Policy Integration: Restrict who can send alerts via Filament policies:

    public static function canAccess(): bool
    {
        return auth()->
    
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