📧 Week 19, Day 3: Email Notifications

Send Email Alerts with Laravel Notifications

📖 Learning Objectives

🎯 What are Laravel Notifications?

Notifications provide a simple API for sending transactional messages across multiple channels like email, SMS, Slack, and database.

Notification Channels:

Channel Description Use Case
Mail 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

📧 Email Configuration

Step 1: Configure SMTP Settings (.env)

# 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
💡 Tip: For Gmail, enable 2-Step Verification and generate an "App Password" from Google Account settings.

Step 2: Test Email Configuration

// 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!'; });

🔔 Creating Notification Classes

Generate Notification:

# Create a notification php artisan make:notification WelcomeNotification # Creates: app/Notifications/WelcomeNotification.php

Basic Notification Structure:

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!'); } }

📨 Sending Notifications

Method 1: Using Notifiable Trait

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'); }

Method 2: Using Notification Facade

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());

🎨 Customizing Email Templates

Rich Email Content:

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'); }

Passing Data to Notifications:

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'));

💾 Database Notifications

Step 1: Create Notifications Table

# Generate migration php artisan notifications:table # Run migration php artisan migrate

Step 2: Add Database Channel

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, ]; }

Step 3: Retrieve Notifications

// 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();

⚡ Queuing Notifications

For better performance, queue notifications to send in the background.

Make Notification Queueable:

use Illuminate\Bus\Queueable; use Illuminate\Contracts\Queue\ShouldQueue; class WelcomeNotification extends Notification implements ShouldQueue { use Queueable; // Rest of notification code... }

Process Queue:

# 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

✍️ Practice Exercises

Exercise 1: Welcome Email

  1. Configure SMTP with Mailtrap
  2. Create WelcomeNotification
  3. Send notification after user registration
  4. Test email delivery

Exercise 2: Order Confirmation

  1. Create OrderConfirmation notification
  2. Pass order ID and total amount
  3. Include "View Order" button
  4. Send after order creation

Exercise 3: Database Notifications

  1. Create notifications table
  2. Add database channel to notification
  3. Display notifications in dashboard
  4. Add mark as read functionality

🎯 Today's Deliverable

✅ Complete Notification System

Requirements:

  • SMTP configured and working
  • Welcome notification on registration
  • Order confirmation notification
  • Database notifications table created
  • Notification list page in dashboard
  • Mark as read functionality

📚 Summary

🔜 What's Next?

In Week 20, we'll build the final project: