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

Alert Bundle Laravel Package

analogic/alert-bundle

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Installation:

    composer require analogic/alert-bundle
    

    Add to config/bundles.php (Laravel 5.5+):

    return [
        // ...
        Analogic\AlertBundle\AnalogicAlertBundle::class => ['all' => true],
    ];
    
  2. Basic Configuration (config/alert.php):

    return [
        'enabled' => env('APP_ENV') !== 'local',
        'prefix' => '[ALERT] ',
        'from' => [
            'email' => 'alerts@yourdomain.com',
            'name' => 'App Alerts',
        ],
        'to' => ['admin@example.com'],
        'ignore' => [
            \Symfony\Component\HttpKernel\Exception\NotFoundHttpException::class,
            \Symfony\Component\HttpKernel\Exception\AccessDeniedHttpException::class,
        ],
    ];
    
  3. First Use Case:

    • PHP Exceptions: Automatically captured for HTTP and CLI commands (if enabled: true).
    • JS Errors: Add to your Blade template:
      <script>{{ javascript_error_listener() }}</script>
      

Implementation Patterns

Core Workflows

  1. Exception Handling:

    • HTTP Requests: Wrap critical routes with try-catch or leverage middleware (e.g., App\Middleware\AlertHandler):
      public function handle($request, Closure $next) {
          try {
              return $next($request);
          } catch (\Exception $e) {
              if (!in_array(get_class($e), config('alert.ignore'))) {
                  alert($e); // Built-in helper (if provided)
              }
              throw $e;
          }
      }
      
    • CLI Commands: Run commands with -e prod to bypass dev environment checks:
      php artisan your:command -e prod
      
  2. JS Error Tracking:

    • Frontend Integration: Include the listener in your base layout (e.g., resources/views/layouts/app.blade.php).
    • Custom Payloads: Extend the JS listener to include user context (e.g., session data):
      window.addEventListener('error', (event) => {
          fetch('/api/alerts/js', {
              method: 'POST',
              body: JSON.stringify({
                  error: event.message,
                  url: window.location.href,
                  user: {{ json_encode(session('user')) }},
              }),
          });
      });
      
  3. Email Spooling:

    • Configure Symfony’s spool transport in config/services.php:
      'mailer' => [
          'dsn' => 'file:///tmp/alerts',
      ],
      
    • Process spool with php bin/console messenger:consume async -vv (or use incron for real-time).

Integration Tips

  • Laravel-Specific:
    • Replace Symfony’s AppKernel with Laravel’s service provider (AnalogicAlertServiceProvider).
    • Use Laravel’s Mail facade for custom email templates:
      use Illuminate\Support\Facades\Mail;
      Mail::raw($alert->getMessage(), function ($message) {
          $message->to(config('alert.to'))
                  ->subject(config('alert.prefix') . 'Alert');
      });
      
  • Logging Fallback: Combine with Laravel’s Log::critical() for redundancy:
    if (!alert($e)) {
        Log::critical('Alert failed', ['exception' => $e]);
    }
    

Gotchas and Tips

Pitfalls

  1. Environment Mismatch:

    • Issue: Alerts disabled in config/alert.php but still triggered in production.
    • Fix: Use env('APP_ENV') !== 'local' and verify APP_ENV in .env.
    • Debug: Add a log entry in the bundle’s AlertListener to confirm environment checks.
  2. Ignored Exceptions:

    • Issue: Critical exceptions (e.g., DatabaseException) are silently ignored.
    • Fix: Explicitly remove from ignore array or use a wildcard:
      'ignore' => [
          '*HttpException', // Ignores all HTTP exceptions
          '!\\Symfony\\Component\\HttpKernel\\Exception\\HttpExceptionInterface', // Exclude specific types
      ],
      
  3. JS Listener Conflicts:

    • Issue: Multiple JS error listeners (e.g., Sentry, Rollbar) interfere.
    • Fix: Debounce events or namespace the listener:
      window.addEventListener('error', (e) => {
          if (e.message.includes('AnalogicAlert')) return;
          // Your logic
      });
      
  4. Spool Overload:

    • Issue: Spool directory fills up with undelivered emails.
    • Fix: Set up a cron job to flush spool daily:
      * * * * * php bin/console messenger:consume async --limit=100
      

Debugging

  • Check Listener Registration:

    • Verify the AlertListener is subscribed to kernel events in AnalogicAlertBundle::boot().
    • Temporarily log events in handleException():
      \Log::debug('Alert triggered', ['exception' => $exception]);
      
  • Email Delivery:

    • Test with a local SMTP server (e.g., MailHog) to avoid spool issues:
      'mailer' => [
          'dsn' => 'smtp://mailhog:1025',
      ],
      

Extension Points

  1. Custom Alert Channels:

    • Extend the bundle to support Slack/Teams by overriding the AlertManager:
      class CustomAlertManager extends \Analogic\AlertBundle\Manager\AlertManager {
          public function send(\Exception $exception) {
              // Custom logic (e.g., Slack API call)
              parent::send($exception); // Fallback to email
          }
      }
      
    • Bind the service in AnalogicAlertServiceProvider.
  2. Dynamic Recipients:

    • Use Laravel’s config('alert.to') to fetch recipients from a database:
      'to' => function () {
          return \App\Models\User::where('role', 'admin')->pluck('email')->toArray();
      },
      
  3. Rich Error Context:

    • Attach additional data (e.g., request payload, user ID) to exceptions:
      $exception = new \RuntimeException('Oops!');
      $exception->setContext(['user_id' => auth()->id(), 'request' => $request->all()]);
      alert($exception);
      
    • Parse this in the bundle’s AlertFormatter.
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.
codifyo/ts-generator-bundle
andydefer/laravel-cluster
testo/fiber
mintobit/jobqueue
a4sex/maintenance-bundle
a4sex/entity-date-update
a4sex/client-identifier
a4sex/base-utilites
a4sex/key-value-storage
a4sex/micro-status
chilldev/dependency-injection-extra
datinglibre/datinglibre-app-api
biberltd/corebundle
bricre/symfony-bundle-test
biberltd/logbundle
dominium/http-adapter-bundle
dominium/google-analytics
a4sex/auto-clean-entity
christhompsontldr/laravel-inky
spatie/mailcoach-vapor