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 Alert Notifications Laravel Package

kevincobain2000/laravel-alert-notifications

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Installation:

    composer require kevincobain2000/laravel-alert-notifications
    

    For Laravel 5.5+, auto-discovery handles the service provider registration. For older versions, manually add to config/app.php:

    'providers' => [
        Kevincobain2000\LaravelAlertNotifications\AlertNotificationsServiceProvider::class,
    ],
    
  2. Publish Config:

    php artisan vendor:publish --provider="Kevincobain2000\LaravelAlertNotifications\AlertNotificationsServiceProvider"
    

    This generates config/laravel_alert_notifications.php. Clear config cache afterward:

    php artisan config:cache
    
  3. Configure Channels: Edit the published config file to enable/disable channels (e.g., email, slack, microsoft_teams) and set credentials (API tokens, email addresses, etc.).

  4. First Use Case: Trigger an exception in your app (e.g., 1/0 in a route or controller). The package will automatically capture it and dispatch notifications to configured channels.


Implementation Patterns

Core Workflow

  1. Exception Handling: The package hooks into Laravel’s exception handler (App\Exceptions\Handler). Exceptions are caught and processed through the AlertNotificationsServiceProvider.

  2. Channel-Specific Notifications:

    • Email: Uses Laravel’s built-in mail system. Configure mail in .env (e.g., MAIL_MAILER=smtp).
      // config/laravel_alert_notifications.php
      'email' => [
          'enabled' => true,
          'to' => ['admin@example.com'],
      ],
      
    • Slack/Microsoft Teams: Requires webhook URLs. Configure in the same file:
      'slack' => [
          'enabled' => true,
          'webhook_url' => env('SLACK_WEBHOOK_URL'),
      ],
      
    • PagerDuty: Needs an integration key:
      'pagerduty' => [
          'enabled' => true,
          'integration_key' => env('PAGERDUTY_INTEGRATION_KEY'),
      ],
      
  3. Throttling: Notifications are throttled by default (configurable in config/laravel_alert_notifications.php under throttle). Use cache driver for shared throttling across hosts:

    'throttle' => [
        'enabled' => true,
        'max_attempts' => 1,
        'decay_minutes' => 1,
        'cache_driver' => 'redis', // or 'database', 'memcached'
    ],
    
  4. Customizing Notifications: Publish views to override default templates:

    php artisan vendor:publish --tag=alert-notifications-views
    

    Modify templates in resources/views/vendor/laravel-alert-notifications/.

  5. Manual Dispatch: Manually trigger notifications for non-exception events (e.g., deployments, cron jobs):

    use Kevincobain2000\LaravelAlertNotifications\Facades\AlertNotifications;
    
    AlertNotifications::send('Custom message', ['key' => 'value']);
    

Integration Tips

  • Environment-Specific Configs: Use .env for sensitive data (e.g., SLACK_WEBHOOK_URL, PAGERDUTY_INTEGRATION_KEY). Example:

    SLACK_WEBHOOK_URL=https://hooks.slack.com/services/xxx
    PAGERDUTY_INTEGRATION_KEY=abc123
    
  • Logging: Combine with Laravel’s logging for debugging. Check storage/logs/laravel.log for exceptions not reaching notifications.

  • Testing: Mock channels in tests to avoid real notifications:

    // In a test
    $this->partialMock(AlertNotifications::class, function ($mock) {
        $mock->shouldReceive('sendToEmail')->andReturnTrue();
    });
    
  • Queue Workers: For high-traffic apps, queue notifications to avoid delays:

    // config/laravel_alert_notifications.php
    'queue' => [
        'enabled' => true,
        'connection' => 'redis',
    ],
    

Gotchas and Tips

Pitfalls

  1. Throttling Overrides: If notifications stop working, check throttling settings. Shared cache (e.g., Redis) may block all hosts if misconfigured.

  2. Channel-Specific Errors:

    • Slack/Microsoft Teams: Invalid webhook URLs will fail silently. Validate URLs before deployment.
    • Email: Ensure MAIL_MAILER and SMTP settings are correct in .env. Test with php artisan tinker:
      Mail::raw('Test', function($message) {
          $message->to('admin@example.com')->subject('Test');
      });
      
  3. Exception Handler Conflicts: If using a custom App\Exceptions\Handler, ensure the package’s exception handler is not overridden. The package registers a middleware (HandleAlertNotifications) automatically.

  4. Lumen Compatibility: Lumen requires manual config/view publishing. Ensure paths in config/laravel_alert_notifications.php match your Lumen setup.

  5. Rate Limiting: PagerDuty may throttle rapid events. Use decay_minutes to space out notifications.


Debugging Tips

  1. Check Cache: Throttling issues? Clear cache:

    php artisan cache:clear
    
  2. Log Exceptions: Add debug logs in App\Exceptions\Handler to trace skipped notifications:

    public function report(Throwable $exception)
    {
        \Log::debug('Exception reported:', ['exception' => $exception]);
    }
    
  3. Test Channels Individually: Use php artisan tinker to test each channel:

    // Test Slack
    AlertNotifications::send('Test Slack', [], 'slack');
    
    // Test Email
    AlertNotifications::send('Test Email', [], 'email');
    
  4. Override Templates: If HTML emails/Slack messages are malformed, override the views:

    php artisan vendor:publish --tag=alert-notifications-views
    

    Edit resources/views/vendor/laravel-alert-notifications/email.blade.php.


Extension Points

  1. Custom Channels: Extend the package by creating a new channel. Implement the ChannelInterface:

    namespace App\Notifications\Channels;
    
    use Kevincobain2000\LaravelAlertNotifications\Contracts\ChannelInterface;
    
    class CustomChannel implements ChannelInterface {
        public function send($message, array $context = [])
        {
            // Custom logic (e.g., HTTP request to a custom API)
        }
    }
    

    Register it in config/laravel_alert_notifications.php:

    'channels' => [
        'custom' => [
            'enabled' => true,
            'class' => App\Notifications\Channels\CustomChannel::class,
        ],
    ],
    
  2. Dynamic Recipients: Use closures in config for dynamic email recipients:

    'email' => [
        'enabled' => true,
        'to' => function () {
            return ['admin@' . config('app.env') . '.com'];
        },
    ],
    
  3. Exception Filtering: Filter exceptions by type or severity in App\Exceptions\Handler:

    public function register()
    {
        $this->renderable(function (Throwable $e, $request) {
            if ($e instanceof \Symfony\Component\HttpKernel\Exception\HttpException && $e->getStatusCode() < 500) {
                return null; // Skip non-server errors
            }
        });
    }
    
  4. Webhook Signatures: For security, validate Slack/PagerDuty webhook signatures. Extend the channel classes to add validation logic.

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.
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
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