laravel-notification-patterns
Best practices for Laravel notifications including multi-channel delivery, mail and database notifications, queueing, and on-demand recipients.
What this skill does
# Notification Patterns
## Notification Class Structure
```php
<?php
namespace App\Notifications;
use Illuminate\Bus\Queueable;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Notifications\Messages\MailMessage;
use Illuminate\Notifications\Notification;
class OrderShipped extends Notification implements ShouldQueue
{
use Queueable;
public function __construct(
public readonly Order $order,
) {}
public function via(object $notifiable): array
{
return ['mail', 'database', 'broadcast'];
}
public function toMail(object $notifiable): MailMessage
{
return (new MailMessage)
->subject('Order Shipped')
->greeting("Hello {$notifiable->name}!")
->line("Your order #{$this->order->number} has been shipped.")
->action('Track Order', url("/orders/{$this->order->id}/track"))
->line('Thank you for your purchase!');
}
public function toArray(object $notifiable): array
{
return [
'order_id' => $this->order->id,
'order_number' => $this->order->number,
'message' => "Order #{$this->order->number} has been shipped.",
];
}
}
```
## Mail Notifications
### MailMessage Builder
```php
public function toMail(object $notifiable): MailMessage
{
return (new MailMessage)
->from('[email protected]', 'App Name')
->subject('Invoice Paid')
->greeting('Hello!')
->line('One of your invoices has been paid.')
->lineIf($this->amount > 100, 'This was a large payment.')
->action('View Invoice', $this->invoiceUrl)
->line('Thank you for using our application!')
->salutation('Regards, The Team');
}
```
### Markdown Mail Templates
```php
public function toMail(object $notifiable): MailMessage
{
return (new MailMessage)
->subject('Order Confirmation')
->markdown('mail.order.confirmed', [
'order' => $this->order,
'url' => route('orders.show', $this->order),
]);
}
```
```blade
{{-- resources/views/mail/order/confirmed.blade.php --}}
<x-mail::message>
# Order Confirmed
Your order **#{{ $order->number }}** has been confirmed.
<x-mail::table>
| Item | Quantity | Price |
|:-----------|:---------|:--------|
@foreach ($order->items as $item)
| {{ $item->name }} | {{ $item->quantity }} | ${{ $item->price }} |
@endforeach
</x-mail::table>
<x-mail::button :url="$url">
View Order
</x-mail::button>
Thanks,<br>
{{ config('app.name') }}
</x-mail::message>
```
### Attachments
```php
public function toMail(object $notifiable): MailMessage
{
return (new MailMessage)
->subject('Monthly Report')
->line('Please find your monthly report attached.')
->attach($this->reportPath, [
'as' => 'report.pdf',
'mime' => 'application/pdf',
])
->attachData($this->csvContent, 'data.csv', [
'mime' => 'text/csv',
]);
}
```
## Database Notifications
### Setup
```bash
php artisan notifications:table
php artisan migrate
```
```php
// Model must use Notifiable trait
use Illuminate\Notifications\Notifiable;
class User extends Authenticatable
{
use Notifiable;
}
```
### Storing Notifications
```php
public function toArray(object $notifiable): array
{
return [
'invoice_id' => $this->invoice->id,
'amount' => $this->invoice->amount,
'message' => "Invoice #{$this->invoice->number} paid.",
];
}
```
### Reading and Managing Notifications
```php
// Get all notifications
$notifications = $user->notifications;
// Get unread notifications
$unread = $user->unreadNotifications;
// Mark as read
$user->unreadNotifications->markAsRead();
// Mark a single notification as read
$notification->markAsRead();
// Mark as unread
$notification->markAsUnread();
// Delete old notifications
$user->notifications()->where('created_at', '<', now()->subMonths(3))->delete();
```
## Broadcast Notifications
```php
use Illuminate\Notifications\Messages\BroadcastMessage;
public function toBroadcast(object $notifiable): BroadcastMessage
{
return new BroadcastMessage([
'invoice_id' => $this->invoice->id,
'amount' => $this->invoice->amount,
]);
}
// Custom channel name (optional)
public function broadcastType(): string
{
return 'invoice.paid';
}
```
```javascript
// Listening with Echo
Echo.private(`App.Models.User.${userId}`)
.notification((notification) => {
console.log(notification.type);
console.log(notification.invoice_id);
});
```
## Slack Notifications
```php
use Illuminate\Notifications\Slack\BlockKit\Blocks\SectionBlock;
use Illuminate\Notifications\Slack\SlackMessage;
public function toSlack(object $notifiable): SlackMessage
{
return (new SlackMessage)
->text("Order #{$this->order->number} shipped")
->headerBlock("Order Shipped")
->sectionBlock(function (SectionBlock $block) {
$block->text("Order *#{$this->order->number}* has been shipped.");
$block->field("*Customer:*\n{$this->order->customer_name}")->markdown();
$block->field("*Tracking:*\n{$this->order->tracking_number}")->markdown();
});
}
```
## Queueing Notifications
### Basic Queueing
```php
// ✅ Implement ShouldQueue
class OrderShipped extends Notification implements ShouldQueue
{
use Queueable;
// Per-channel queue configuration
public function viaQueues(): array
{
return [
'mail' => 'mail-queue',
'database' => 'default',
'slack' => 'slack-queue',
];
}
}
```
### After Commit
```php
// ✅ Only dispatch after database transaction commits
class OrderShipped extends Notification implements ShouldQueue
{
use Queueable;
public $afterCommit = true;
}
```
### Delayed Notifications
```php
$user->notify(
(new OrderShipped($order))->delay([
'mail' => now()->addMinutes(5),
'database' => now(),
])
);
```
### Retry and Failure Handling
```php
class OrderShipped extends Notification implements ShouldQueue
{
use Queueable;
public $tries = 3;
public $backoff = [30, 60, 120];
public function failed(\Throwable $exception): void
{
// Handle failure (log, alert, etc.)
Log::error('OrderShipped notification failed', [
'order_id' => $this->order->id,
'error' => $exception->getMessage(),
]);
}
}
```
## Conditional Sending
```php
public function shouldSend(object $notifiable, string $channel): bool
{
// Don't send mail if user disabled email notifications
if ($channel === 'mail') {
return $notifiable->prefers_email_notifications;
}
// Don't notify about small amounts
return $this->invoice->amount > 10;
}
```
## On-Demand Notifications
```php
use Illuminate\Support\Facades\Notification;
// ✅ Send to an email address without a user model
Notification::route('mail', '[email protected]')
->route('slack', '#alerts')
->notify(new ServerHealthReport($server));
// ✅ With recipient name
Notification::route('mail', ['[email protected]' => 'Admin User'])
->notify(new WeeklyDigest());
```
## Sending Notifications
```php
use Illuminate\Support\Facades\Notification;
// Via the Notifiable trait
$user->notify(new OrderShipped($order));
// Via the Notification facade (multiple recipients)
Notification::send($users, new OrderShipped($order));
// ❌ Don't loop to send individually
foreach ($users as $user) {
$user->notify(new OrderShipped($order)); // Inefficient
}
// ✅ Send to a collection
Notification::send(User::all(), new SystemAnnouncement($message));
```
## Custom Notification Channels
```php
class SmsChannel
{
public function send(object $notifiable, Notification $notification): void
{
$message = $notification->toSms($notifiable);
$phone = $notifiable->routeNotificationFor('sRelated in General
modeling-omnistudio-epc-catalog
IncludedSalesforce Industries CME EPC product-modeling skill for Product2-based catalog creation. Use when creating EPC products, configuring product attributes, building offer bundles with Product Child Items, or reviewing EPC DataPack JSON metadata for product catalog changes. TRIGGER when: user creates or updates Product2 EPC records, AttributeAssignment payloads, AttributeMetadata/AttributeDefaultValues, Offer bundles, or ProductChildItem relationships. DO NOT TRIGGER when: designing OmniScripts/FlexCards/Integration Procedures (use building-omnistudio-omniscript, building-omnistudio-flexcard, or building-omnistudio-integration-procedure), implementing Apex business logic (use generating-apex), or troubleshooting deployment pipelines (use deploying-metadata).
relationship-science-coach
IncludedUse this skill for direct, practical adult relationship coaching: couples conflict, repair, trust, marriage, dating, flirting, attachment patterns, emotional connection, sex, desire differences, eroticism, kink negotiation, affection, love languages, breakups, and long-term passion. Draw on Gottman, EFT and Hold Me Tight, attachment science, modern sex research, Perel, Nagoski, Kerner, Schnarch, Love and Stosny, and flexible love-language tools. Be concrete and low-hedge. Redirect only for imminent danger, abuse, coercive control, minors, non-consent, self-harm, stalking, or medical/legal/psychiatric decisions.
building-sf-integrations
IncludedSalesforce integration architecture and runtime plumbing with 120-point scoring. Use this skill to set up Named Credentials, External Credentials, External Services, REST/SOAP callout patterns, Platform Events, and Change Data Capture. TRIGGER when: user sets up Named Credentials, External Services, REST/SOAP callouts, Platform Events, CDC, or touches .namedCredential-meta.xml files. DO NOT TRIGGER when: Connected App/OAuth config (use configuring-connected-apps), Apex-only logic (use generating-apex), or data import/export (use handling-sf-data).
venue-templates
IncludedAccess comprehensive LaTeX templates, formatting requirements, and submission guidelines for major scientific publication venues (Nature, Science, PLOS, IEEE, ACM), academic conferences (NeurIPS, ICML, CVPR, CHI), research posters, and grant proposals (NSF, NIH, DOE, DARPA). This skill should be used when preparing manuscripts for journal submission, conference papers, research posters, or grant proposals and need venue-specific formatting requirements and templates.
let-fate-decide
IncludedDraws the 12 Houses of the Zodiac Tarot spread to inject entropy into planning when prompts are vague, ambiguous, or casually delegated. Interprets the spread to guide next steps. Use when the user says 'let fate decide', 'YOLO', 'whatever', 'idk', or other nonchalant phrases, makes Yu-Gi-Oh references, or when you are about to arbitrarily pick between multiple reasonable approaches. Prefer over ask-questions-if-underspecified when the user's tone is casual or playful rather than precision-seeking.
net-ops
IncludedCross-platform network troubleshooting (Windows, macOS, Linux) via local or remote shell. Use for: DNS broken, can't resolve hostnames, nslookup/dig works but apps fail, NRPT, WFP, scutil, /etc/resolver, systemd-resolved, /etc/resolv.conf, NetworkManager, VPN DNS leak residue (ProtonVPN/Mullvad/WireGuard/AnyConnect), AV/firewall blocking DNS or DoH, Tailscale DNS interaction, intermittent connectivity, remote diagnostics over SSH.