Send Email Alerts with Laravel Notifications
Notifications provide a simple API for sending transactional messages across multiple channels like email, SMS, Slack, and database.
| Channel | Description | Use Case |
|---|---|---|
| Send emails via SMTP | Welcome emails, password resets | |
| Database | Store in notifications table | In-app notifications |
| SMS | Send text messages | 2FA codes, alerts |
| Slack | Post to Slack channels | Team alerts |
# For Gmail
MAIL_MAILER=smtp
MAIL_HOST=smtp.gmail.com
MAIL_PORT=587
MAIL_USERNAME=your-email@gmail.com
MAIL_PASSWORD=your-app-password
MAIL_ENCRYPTION=tls
MAIL_FROM_ADDRESS=your-email@gmail.com
MAIL_FROM_NAME="${APP_NAME}"
# For Mailtrap (Testing)
MAIL_MAILER=smtp
MAIL_HOST=sandbox.smtp.mailtrap.io
MAIL_PORT=2525
MAIL_USERNAME=your-mailtrap-username
MAIL_PASSWORD=your-mailtrap-password
MAIL_ENCRYPTION=tls
// routes/web.php
use Illuminate\Support\Facades\Mail;
Route::get('/test-email', function () {
Mail::raw('Test email from Laravel!', function ($message) {
$message->to('test@example.com')
->subject('Test Email');
});
return 'Email sent!';
});
# Create a notification
php artisan make:notification WelcomeNotification
# Creates: app/Notifications/WelcomeNotification.php
namespace App\Notifications;
use Illuminate\Notifications\Notification;
use Illuminate\Notifications\Messages\MailMessage;
class WelcomeNotification extends Notification
{
// Define notification channels
public function via($notifiable)
{
return ['mail'];
}
// Define email content
public function toMail($notifiable)
{
return (new MailMessage)
->subject('Welcome to Our Platform!')
->greeting('Hello ' . $notifiable->name . '!')
->line('Thank you for registering.')
->action('Visit Dashboard', url('/dashboard'))
->line('We hope you enjoy our service!');
}
}
use App\Notifications\WelcomeNotification;
// Send to single user
$user = User::find(1);
$user->notify(new WelcomeNotification());
// Send after user registration
public function store(Request $request)
{
$user = User::create([
'name' => $request->name,
'email' => $request->email,
'password' => Hash::make($request->password),
]);
// Send welcome email
$user->notify(new WelcomeNotification());
return redirect('/dashboard');
}
use Illuminate\Support\Facades\Notification;
// Send to multiple users
$users = User::where('active', true)->get();
Notification::send($users, new WelcomeNotification());
// Send to specific email (on-demand)
Notification::route('mail', 'admin@example.com')
->notify(new WelcomeNotification());
public function toMail($notifiable)
{
return (new MailMessage)
->subject('Order Confirmation')
->greeting('Hello ' . $notifiable->name)
->line('Your order has been confirmed!')
->line('Order #: ' . $this->orderId)
->action('View Order', url('/orders/' . $this->orderId))
->line('Thank you for shopping with us!')
->salutation('Best regards, Our Team');
}
class OrderShipped extends Notification
{
public $orderId;
public $trackingNumber;
public function __construct($orderId, $trackingNumber)
{
$this->orderId = $orderId;
$this->trackingNumber = $trackingNumber;
}
public function toMail($notifiable)
{
return (new MailMessage)
->subject('Order Shipped!')
->line('Order #' . $this->orderId . ' has shipped.')
->line('Tracking: ' . $this->trackingNumber);
}
}
// Usage
$user->notify(new OrderShipped(123, 'ABC123XYZ'));
# Generate migration
php artisan notifications:table
# Run migration
php artisan migrate
public function via($notifiable)
{
return ['mail', 'database']; // Both channels
}
public function toDatabase($notifiable)
{
return [
'title' => 'New Comment',
'message' => 'Someone commented on your post',
'post_id' => $this->postId,
];
}
// Get all notifications
$notifications = auth()->user()->notifications;
// Get unread notifications
$unread = auth()->user()->unreadNotifications;
// Mark as read
auth()->user()->unreadNotifications->markAsRead();
// Mark single notification as read
$notification = auth()->user()->notifications()->find($id);
$notification->markAsRead();
For better performance, queue notifications to send in the background.
use Illuminate\Bus\Queueable;
use Illuminate\Contracts\Queue\ShouldQueue;
class WelcomeNotification extends Notification implements ShouldQueue
{
use Queueable;
// Rest of notification code...
}
# Start queue worker
php artisan queue:work
# Or use database driver in .env
QUEUE_CONNECTION=database
# Create jobs table
php artisan queue:table
php artisan migrate
Requirements:
In Week 20, we'll build the final project: