Installation
composer require b2pweb/bdf-event-notifier
Publish the config file (if available):
php artisan vendor:publish --provider="B2PWeb\BDFEventNotifier\BDFEventNotifierServiceProvider"
Basic Configuration
Check config/bdf-event-notifier.php for default settings (e.g., default channels, retry logic, or logging). Override as needed:
'channels' => [
'mail' => [
'enabled' => true,
'from' => 'notifications@example.com',
],
'slack' => [
'enabled' => false,
'webhook' => env('SLACK_WEBHOOK'),
],
],
First Use Case: Notifying on User Registration
Dispatch an event in your UserController:
use B2PWeb\BDFEventNotifier\Facades\EventNotifier;
use App\Events\UserRegistered;
public function register(Request $request)
{
$user = User::create($request->validated());
EventNotifier::notify(new UserRegistered($user));
}
Define a listener for the event (e.g., app/Listeners/NotifyUserRegistered.php):
public function handle(UserRegistered $event)
{
EventNotifier::send('mail', new UserRegisteredMail($event->user));
}
Register the listener in EventServiceProvider:
protected $listen = [
UserRegistered::class => [
NotifyUserRegistered::class,
],
];
Decoupled Notifications
Use the package’s EventNotifier facade to send notifications without coupling to specific channels:
EventNotifier::send('mail', new InvoicePaidMail($invoice));
EventNotifier::send('slack', new SlackAlert($invoice));
Dynamic Channel Routing Route notifications dynamically based on user preferences or event metadata:
$channels = $user->preferredNotificationChannels; // e.g., ['mail', 'slack']
foreach ($channels as $channel) {
EventNotifier::send($channel, new GenericAlert($event));
}
Batch Processing Process events in bulk (e.g., for analytics or reporting):
$events = Event::where('processed', false)->limit(100)->get();
foreach ($events as $event) {
EventNotifier::notify($event);
}
Event::whereIn('id', $events->pluck('id'))->update(['processed' => true]);
Laravel Events Extend existing Laravel events or create custom ones. Example:
class OrderShipped implements ShouldQueue
{
public function __construct(public Order $order) {}
}
Queue Integration
Leverage Laravel queues for async processing. Ensure your events implement ShouldQueue:
EventNotifier::notify(new OrderShipped($order))->onQueue('notifications');
Testing
Mock the EventNotifier facade in tests:
$this->mock(EventNotifier::class)->shouldReceive('send')->once();
Channel Configuration
config/bdf-event-notifier.php will silently fail.if (!config('bdf-event-notifier.channels.mail.enabled')) {
throw new \RuntimeException('Mail channel is disabled.');
}
Event Serialization
->onQueue() with serialize: false or implement __serialize() in your event:
public function __serialize()
{
return ['user_id' => $this->user->id];
}
Duplicate Notifications
processed_at timestamp to your events table and deduplicate:
if ($event->processed_at) return;
$event->update(['processed_at' => now()]);
Log Notifications Enable logging in the config:
'log' => [
'enabled' => true,
'channel' => 'single',
],
Check storage/logs/laravel.log for failed notifications.
Channel-Specific Errors
Wrap channel logic in try-catch blocks to log errors per channel:
try {
EventNotifier::send('slack', $alert);
} catch (\Exception $e) {
\Log::error("Slack notification failed: " . $e->getMessage());
}
Custom Channels
Create a new channel driver by implementing B2PWeb\BDFEventNotifier\Contracts\Channel:
class TeamsChannel implements Channel
{
public function send($event)
{
// Custom logic for Microsoft Teams
}
}
Register it in the config:
'channels' => [
'teams' => [
'enabled' => true,
'webhook' => env('TEAMS_WEBHOOK'),
],
],
Event Transformers Use transformers to modify payloads before sending:
EventNotifier::send('mail', new UserRegisteredMail($user))
->transform(fn ($payload) => [
'subject' => "Welcome, {$payload['user']['name']}!",
// ...
]);
Middleware Add middleware to events (e.g., for rate limiting or auth):
EventNotifier::notify($event)->through([ThrottleNotifications::class]);
How can I help you explore Laravel packages today?