Custom Notification System in Laravel

Posted on January 17th, 2025

Notifications are essential to modern web applications, helping keep users informed of updates, alerts, and important events. While Laravel provides built-in support for notifications with channels like email, SMS, and Slack, sometimes you need a customized solution tailored to your requirements.

This guide will walk you through building a custom notification system in Laravel from scratch. We will cover creating a notification model, setting up the database, and sending and displaying notifications to users. By building a custom system, you can gain complete control over how notifications are stored, delivered, and managed, creating a unique experience tailored specifically to your application’s needs.

In this tutorial, we will cover:

  • Setting Up the Laravel Project
  • Creating the Notification Model and Migration
  • Setting Up Notification Channels
  • Sending Custom Notifications
  • Displaying Notifications to Users
  • Marking Notifications as Read
  • Advanced Features and Customization
  • Testing and Debugging

By the end of this guide, you will be able to build a flexible, scalable notification system in Laravel that can be easily adapted to fit any application’s needs.

Why Build a Custom Notification System?

  • Tailored User Experience: Customize notifications to meet your application’s unique requirements, enhancing user engagement.
  • Scalability: Manage large volumes of notifications with more control over how and when they are delivered.
  • Flexibility: Easily extend and integrate new notification channels as your application grows.
  • Enhanced Management: Gain better control over notification tracking, read statuses, and custom logic.

Prerequisites

  • Basic Knowledge of Laravel: Understanding of routes, controllers, and models.
  • Laravel Project: A Laravel application set up. If not, create one using Composer.

Step-by-Step Guide

Now that you have an overview of what this guide will cover, let’s dive in and start the step-by-step process to build your custom notification system.

Step 1: Set Up Your Laravel Project

Start by creating a new Laravel project if you haven’t already:

composer create-project --prefer-dist laravel/laravel custom-notification-system
cd custom-notification-system

Step 2: Create the Notification Model and Migration

First, create a Notification model and migration to store notifications in the database:

php artisan make:model Notification -m

This command creates a new model and migration file. Open the migration file (database/migrations/xxxx_xx_xx_create_notifications_table.php) and add the necessary fields:

Schema::create('notifications', function (Blueprint $table) {
    $table->id();
    $table->foreignId('user_id')->constrained()->onDelete('cascade');
    $table->string('type'); // Type of notification (e.g., info, alert)
    $table->text('data'); // JSON data for the notification
    $table->boolean('is_read')->default(false);
    $table->timestamps();
});

Run the migration to create the notifications table:

php artisan migrate

Step 3: Set Up Notification Channels

Laravel’s built-in notifications support various channels, but you can customize or add new channels. Start by setting up a notification class:

php artisan make:notification CustomNotification

In the CustomNotification class (app/Notifications/CustomNotification.php), define how the notification will be delivered:

<?php
namespace App\Notifications;
use Illuminate\Bus\Queueable;
use Illuminate\Notifications\Notification;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Notifications\Messages\MailMessage;
class CustomNotification extends Notification implements ShouldQueue
{
    use Queueable;
    private $data;
    public function __construct($data)
    {
        $this->data = $data;
    }
    public function via($notifiable)
    {
        return ['database']; // Storing in the database; you can add more channels like 'mail', 'sms', etc.
    }
    public function toArray($notifiable)
    {
        return [
            'message' => $this->data['message'],
            'url' => $this->data['url'] ?? '#',
        ];
    }
}

Step 4: Sending Custom Notifications

You can use the notify method on the user model to send notifications. First, ensure the Notifiable trait is used in your User model (app/Models/User.php):

<?php
namespace App\Models;
use Illuminate\Foundation\Auth\User as Authenticatable;
use Illuminate\Notifications\Notifiable;
class User extends Authenticatable
{
    use Notifiable;
    // Other user model code...
}

Send a custom notification from your controller or any part of your application:

use App\Models\User;
use App\Notifications\CustomNotification;
$user = User::find(1); // Get the user to notify
$data = [
    'message' => 'Your order has been shipped!',
    'url' => '/orders/123',
];
$user->notify(new CustomNotification($data));

Step 5: Displaying Notifications to Users

Display notifications in your application by fetching them from the database. In your controller, retrieve notifications for a logged-in user:

public function showNotifications()
{
    $notifications = auth()->user()->notifications()->where('is_read', false)->get();
    return view('notifications.index', compact('notifications'));
}

Create a Blade view (resources/views/notifications/index.blade.php) to display notifications:

<ul>
    @foreach($notifications as $notification)
        <li>
            <a href="{{ $notification->data['url'] }}">
                {{ $notification->data['message'] }}
            </a>
            <small>{{ $notification->created_at->diffForHumans() }}</small>
        </li>
    @endforeach
</ul>

Step 6: Marking Notifications as Read

Add a method in your controller to mark notifications as read:

public function markAsRead($id)
{
    $notification = auth()->user()->notifications()->find($id);
    if ($notification) {
        $notification->markAsRead();
    }
    return redirect()->back();
}

Step 7: Advanced Features and Customization

To make your notification system more advanced and user-friendly, consider implementing the following:

    • Queuing Notifications: Use Laravel’s job queues to handle large volumes of notifications efficiently.
public function via($notifiable)
{
    return ['database', 'mail']; // Example of adding email channel
}
  • Adding Notification Preferences: Allow users to customize their notification settings, such as turning specific channels on/off.
  • Batch Notifications: Group similar notifications into a single batch to avoid overwhelming the user.
  • Notification Scheduling: Schedule notifications to be sent at specific times using Laravel’s Schedule feature.

Step 8: Testing and Debugging

Test Notifications: Verify that notifications are sent correctly and displayed to the user.

Check Different Channels: If using multiple channels, ensure each works as expected.

Handle Errors Gracefully: Ensure that errors in notification delivery are handled without breaking the user experience.

Usage Benefits

  • Customizable: Easily adapt the notification system to fit your application’s needs.
  • Scalable: Supports large volumes of notifications, with options to queue and process them in the background.
  • User-Friendly: Keep users informed and engaged with timely updates and alerts.
  • Improved User Control: Allows users to control their notification settings, enhancing user experience.

Conclusion

Building a custom notification system in Laravel allows you to tailor how your application communicates with its users. From storing notifications in the database to sending them via multiple channels, Laravel’s flexible architecture makes it easy to extend and customize. Implementing advanced features such as queuing, preferences, and scheduling can significantly enhance your system, ensuring users receive timely, relevant information that suits them best. Start implementing your notification system today to enhance user engagement and inform them about important events.

Leave a Reply