DEV Community

Dhiecoderweb
Dhiecoderweb

Posted on Originally published at dhiecoderweb.com

How to Build Notifications in Laravel (DB & Email)

A notification system is an important feature in almost every modern web application — from new order alerts and email verification to account activity warnings. Laravel has a very flexible built-in notification system that supports various channels such as email, database, SMS, and Slack. In this tutorial, we will focus on the two most common channels: database and email.

Preparation: The Database Notifications Table

For the database notification channel, Laravel needs a dedicated table. Create it with the command:

php artisan make:notifications-table
php artisan migrate
Enter fullscreen mode Exit fullscreen mode

This creates a notifications table that stores notifications in JSON format.

Creating the Notification Class

Create a notification class using Artisan:

php artisan make:notification OrderPlaced
Enter fullscreen mode Exit fullscreen mode

The file will be created at app/Notifications/OrderPlaced.php. Edit that file:

<?php

namespace App\Notifications;

use Illuminate\Bus\Queueable;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Notifications\Messages\MailMessage;
use Illuminate\Notifications\Notification;

class OrderPlaced extends Notification implements ShouldQueue
{
    use Queueable;

    public function __construct(
        protected array $orderData
    ) {}

    // Define which channels to use
    public function via(object $notifiable): array
    {
        return ['database', 'mail'];
    }

    // Content for the email
    public function toMail(object $notifiable): MailMessage
    {
        return (new MailMessage)
            ->subject('Your Order Was Placed Successfully!')
            ->greeting('Hello, ' . $notifiable->name . '!')
            ->line('Your order #' . $this->orderData['order_number'] . ' has been received successfully.')
            ->line('Total payment: $' . number_format($this->orderData['total'], 2))
            ->action('View Order', url('/orders/' . $this->orderData['order_id']))
            ->line('Thank you for shopping with us!');
    }

    // Content for the database
    public function toDatabase(object $notifiable): array
    {
        return [
            'order_id'     => $this->orderData['order_id'],
            'order_number' => $this->orderData['order_number'],
            'total'        => $this->orderData['total'],
            'message'      => 'Order #' . $this->orderData['order_number'] . ' was placed successfully.',
        ];
    }
}
Enter fullscreen mode Exit fullscreen mode

This is only part of the article. For the full discussion, with examples and step-by-step details, you can read it on the original source:

How to Build Notifications in Laravel (DB & Email)

More programming tutorials and developer tools are also available at dhiecoderweb.com.

Top comments (0)