8.8 KiB
8.8 KiB
Multi-Channel Notifications - Quick Start Guide
What's Been Completed
✅ Database Migration
- Migration created:
database/migrations/2026_01_18_123539_add_notification_channels_to_users_table.php - Adds fields for all notification channels to users table
- Run with:
./vendor/bin/sail artisan migrate
✅ Packages Installed
"laravel/slack-notification-channel": "^3.7",
"laravel-notification-channels/telegram": "^6.0",
"laravel-notification-channels/discord": "^1.7"
✅ User Model Updated
- Added fillable fields for all notification channels
- Added
notification_channelsJSON cast - Added helper methods:
getNotificationChannelsFor($alertType)- Get enabled channels for an alert typerouteNotificationForSlack()- Slack webhook routingrouteNotificationForTelegram()- Telegram chat ID routingrouteNotificationForDiscord()- Discord webhook routing
Quick Implementation Steps
Step 1: Run Migration
./vendor/bin/sail artisan migrate
Step 2: Create Notification Classes
All notification class templates are in MULTI_CHANNEL_NOTIFICATIONS_GUIDE.md. Copy them to:
app/Notifications/MonitorAlert.php(base class)app/Notifications/UptimeAlert.phpapp/Notifications/SslExpiryAlert.phpapp/Notifications/DomainExpiryAlert.phpapp/Notifications/SitemapAlert.phpapp/Notifications/PerformanceAlert.php
Step 3: Create Notification Settings Controller
./vendor/bin/sail artisan make:controller NotificationSettingsController
Step 4: Update Existing Jobs
Example - Update CheckSitemap job:
// Replace the sendAlert method in app/Jobs/CheckSitemap.php
use App\Notifications\SitemapAlert;
protected function sendAlert(string $message): void
{
// Send via new notification system
$this->sitemap->site->user->notify(
new SitemapAlert(
$this->sitemap->site->name,
$this->sitemap->url,
$this->sitemap->last_error
)
);
}
Step 5: Add Environment Variables
Add to .env:
# Telegram Bot (optional)
TELEGRAM_BOT_TOKEN=your_bot_token
# Twilio SMS (optional)
TWILIO_SID=your_sid
TWILIO_TOKEN=your_token
TWILIO_FROM=+1234567890
Default Notification Channels Structure
The notification_channels JSON field stores preferences like this:
{
"uptime": ["email", "slack"],
"ssl": ["email", "telegram", "slack"],
"domain_expiry": ["email"],
"sitemap": ["database"],
"performance": ["slack"],
"dns": ["email", "database"],
"broken_links": ["database"],
"health_check": ["email", "slack"],
"tcp_port": ["database"]
}
Supported Channels
Built-in (No Additional Setup)
mail- Email notificationsdatabase- Store in notifications table
Webhook-based (Requires URL)
slack- Requiresslack_webhook_urldiscord- Requiresdiscord_webhook_urltelegram- Requirestelegram_chat_idand bot tokenteams- Requiresteams_webhook_urlgoogle_chat- Requiresgoogle_chat_webhook_urlwebhook- Requireswebhook_url(custom endpoint)
API-based (Requires Credentials)
sms- Requires Twilio/Vonage setupopsgenie- Requiresopsgenie_api_keypagerduty- Requirespagerduty_integration_key
Testing Notifications
Create a test route to verify notifications work:
// In routes/web.php
Route::get('/test-notification', function () {
auth()->user()->notify(
new \App\Notifications\UptimeAlert(
'Test Site',
false, // not down
200,
'https://example.com',
150.5
)
);
return 'Notification sent! Check your configured channels.';
})->middleware('auth');
Setting Up Notification Channels
Slack
- Go to https://api.slack.com/messaging/webhooks
- Create an Incoming Webhook for your workspace
- Copy the webhook URL
- Save in user settings:
slack_webhook_url
Telegram
- Talk to @BotFather on Telegram
- Create a new bot with
/newbot - Save the bot token to
.envasTELEGRAM_BOT_TOKEN - Start a chat with your bot
- Get your chat ID from @userinfobot
- Save in user settings:
telegram_chat_id
Discord
- Go to Server Settings → Integrations → Webhooks
- Create New Webhook
- Copy the Webhook URL
- Save in user settings:
discord_webhook_url
Microsoft Teams
- In Teams, go to channel → Connectors
- Configure "Incoming Webhook"
- Copy the webhook URL
- Save in user settings:
teams_webhook_url
Notification Settings UI (To Be Created)
Create a settings page where users can:
- Enable/disable channels per alert type
- Configure webhook URLs and API keys
- Test notification delivery
- Set quiet hours
- Configure notification preferences
Integration with Existing Monitoring
Update these jobs to send notifications:
app/Jobs/CheckSitePing.php→ UseUptimeAlertapp/Jobs/CheckSslCertificate.php→ UseSslExpiryAlertapp/Jobs/CheckDomainExpiry.php→ UseDomainExpiryAlertapp/Jobs/CheckSitemap.php→ UseSitemapAlertapp/Jobs/CheckHealth.php→ UsePerformanceAlert
Queue Configuration
Notifications are queued by default. Ensure queue worker is running:
./vendor/bin/sail artisan queue:work
Or configure supervisor in production.
Notification Flow
Monitor Job Detects Issue
↓
Creates Notification Object
↓
User::notify(new Alert(...))
↓
Laravel checks via()
↓
Gets enabled channels from user preferences
↓
Dispatches to each channel
↓
Queues notification jobs
↓
Worker processes notifications
↓
Sends to: Email, Slack, Telegram, etc.
Security Considerations
- Encrypt sensitive fields - Consider encrypting webhook URLs and API keys
- Rate limiting - Prevent notification spam
- Validate webhooks - Verify webhook URLs before saving
- Sanitize data - Clean user input in notifications
- HTTPS only - Only allow HTTPS webhook URLs
Troubleshooting
Notifications not sending
- Check queue worker is running:
ps aux | grep queue - Check failed jobs:
./vendor/bin/sail artisan queue:failed - Review logs:
storage/logs/laravel.log - Verify user has configured channels
- Test with simple email notification first
Channel-specific issues
Slack: "Invalid webhook URL"
- Verify URL format: https://hooks.slack.com/services/...
- Check workspace hasn't revoked webhook
Telegram: "Bad Request: chat not found"
- Verify chat ID is correct
- Ensure bot token is valid
- Start conversation with bot first
Discord: "Webhook not found"
- Check webhook wasn't deleted
- Verify URL hasn't expired
Performance Tips
- Use queues - Always queue notifications
- Batch similar alerts - Group notifications when possible
- Debounce - Prevent rapid repeated notifications
- Cache user preferences - Cache notification_channels
- Async webhooks - Don't wait for webhook responses
Next Steps
- Create UI - Build notification settings interface
- Add more channels - Implement Teams, Google Chat, etc.
- Test thoroughly - Test each channel
- Update docs - Document for your team
- Monitor - Track notification success rates
Example: Full Integration
Here's how to fully integrate with an existing job:
<?php
namespace App\Jobs;
use App\Models\Site;
use App\Notifications\UptimeAlert;
use Illuminate\Bus\Queueable;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Foundation\Bus\Dispatchable;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Queue\SerializesModels;
use Illuminate\Support\Facades\Http;
class CheckSiteUptime implements ShouldQueue
{
use Dispatchable, InteractsWithQueue, Queueable, SerializesModels;
public function __construct(
public Site $site
) {
}
public function handle(): void
{
$response = Http::timeout(10)->get($this->site->url);
$isDown = !$response->successful();
$statusCode = $response->status();
$responseTime = $response->transferStats->getTransferTime() * 1000;
// Check if status changed
$previousStatus = $this->site->latestUptimeCheck->is_online ?? true;
// Send notification if status changed
if ($isDown !== !$previousStatus) {
$this->site->user->notify(
new UptimeAlert(
$this->site->name,
$isDown,
$statusCode,
$this->site->url,
$responseTime
)
);
}
// Save check result...
}
}
Resources
- Laravel Notifications: https://laravel.com/docs/notifications
- Slack API: https://api.slack.com/
- Telegram Bot API: https://core.telegram.org/bots/api
- Discord Webhooks: https://discord.com/developers/docs/resources/webhook