Laravel Notification System: Elevate Your User Engagement Strategy

laravel's notification system

Notifications are crucial for keeping users engaged and informed in modern web applications. Laravel’s Notification System allows you to send alerts through various channels like email, SMS, and databases, making it an essential tool for any Laravel project. Whether you’re notifying users about updates or events, this system ensures timely and efficient communication.

In this blog, we’ll cover everything you need to know to get started with Laravel notifications. We’ll begin with the prerequisites and learn how Laravel development experts set up notification systems. Additionally, we’ll help you learn advanced tips and tricks for setting up Laravel notifications. With that said, let’s dive in!

How Does Laravel Notification System Work?

Laravel’s notification system stands as a denotation of user engagement and information delivery. It offers a communication hub, where relevant updates and alerts reach users through their preferred channels. Encouraging awareness and connection.

  • Event-Driven Notifications: Triggered by specific events within your application. Notifications are automatically generated and personalized, delivering targeted information that resonates with users.
  • Multi-Channel Delivery: Whether it’s email, SMS, or even integration with platforms like Slack. The system adapts to user preferences and reaches them on their preferred communication channels.
  • Seamless Integration: Notifications can be integrated into your application’s UI. Providing an intuitive and consistent user experience that keeps them informed without leaving the platform.

Laravel’s notification system provides the tools and the platform, enabling you to build applications that resonate with your audience. You can design personalized messages, explore diverse channels, and integrate them into your user interface.

Prerequisites for Creating Laravel Notification System

Before diving into Laravel’s Notification System, there are a few basic requirements that need to be in place. Ensure that your project is set up and ready to go with the following prerequisites:

  • A Laravel project set up with Laravel Breeze, utilizing the Blade templating engine.
  • Authentication already enabled through Breeze.
  • A basic understanding of Laravel’s framework and its components.

Once these prerequisites are met, you’re ready to explore Laravel’s Notification System and integrate it into your project seamlessly.

Struggling to build a Laravel site with real-time notification system?

How to Set up a Laravel Notification System?

To implement Laravel Notifications, follow these structured steps to ensure smooth integration. We’ll guide you through creating the notification class, configuring the environment, setting up routes, and displaying notifications in the Blade view.

Step 1: Create the Notification Class

First, you need to generate a new notification class. This will allow you to define the content and delivery channels for your notification. Run the following Artisan command to generate the notification:

php artisan make:notification TaskCompleted

This command will create a new file TaskCompleted.php in the app/Notifications/ directory. In this class, we’ll define how the notification is delivered, its content, and the channels it will use.

Code: app/Notifications/TaskCompleted.php

<?php
namespace App\Notifications;
use Illuminate\Bus\Queueable;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Notifications\Messages\MailMessage;
use Illuminate\Notifications\Notification;
class TaskCompleted extends Notification
{
    use Queueable;
    private $task;
    public function __construct($task)
    {
        $this->task = $task;
    }
    public function via($notifiable)
    {
       return ['mail', 'database']; // Deliver via email and store in the database
    }
    public function toMail($notifiable)
    {
        return (new MailMessage)
                    ->subject('Task Completed')
                    ->line('Notification from WpWeb Infotech.')
                    ->line($this->task)
                    ->action('View Notifications', url('/notifications'))
                    ->line('Thank you for using our application!');
    }
    public function toArray($notifiable)
    {
        return [
            'task' => $this->task,
            'message' => 'Notification from WpWeb Infotech: ' . $this->task,
        ];
    }
}

This code defines the TaskCompleted notification class. It uses the Queueable trait to queue the notification for delivery, and it specifies two delivery channels: email (toMail) and database (toArray). The constructor accepts a $task parameter, which represents the task message that will be included in the notification.

Step 2: Configure Mail Setup

Ensure that your .env file is set up correctly with mail credentials. You can use Mailtrap for testing your mail notifications. In your .env file, add the following configuration:

MAIL_MAILER=smtp
MAIL_HOST=smtp.mailtrap.io
MAIL_PORT=2525
MAIL_USERNAME=your_username
MAIL_PASSWORD=your_password
MAIL_ENCRYPTION=tls
MAIL_FROM_ADDRESS=your_email@example.com
MAIL_FROM_NAME="${APP_NAME}"

This configuration sets up the mail driver and SMTP details. Mailtrap is a service that helps you catch emails during development for testing purposes, preventing them from being sent to real recipients.

Step 3: Create Database Notifications Table

To store notifications in the database, generate the migration for the notifications table and run it. Here is the command to do so:

php artisan notifications:table
php artisan migrate

The notifications:table command generates the migration to create a table for storing notifications in the database. The migrate command then runs the migration to apply the changes to your database, allowing notifications to be saved for users.

Step 4: Define Routes

Add the necessary routes in the routes/web.php file to handle sending and displaying notifications.

Code: routes/web.php

use App\Notifications\TaskCompleted;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Route;
use App\Http\Controllers\NotificationController;
// Route to send a notification to the authenticated user
Route::middleware('auth')->get('/send-notification', function () {
    $user = Auth::user(); // Get the authenticated user
    $task = 'This is a test notification sent via Laravel by WpWeb Infotech.';
    $user->notify(new TaskCompleted($task)); // Send notification
    return redirect()->route('notifications.index')->with('success', 'Notification sent successfully!');
})->name('send_notification');
// Routes to manage and display notifications
Route::middleware('auth')->group(function () {
    Route::get('/notifications', [NotificationController::class, 'index'])->name('notifications.index');
    Route::patch('/notifications/{id}/read', [NotificationController::class, 'markAsRead'])->name('notifications.read');
});

This code sets up the routes to send a notification and manage notifications. The /send-notification route sends the notification to the authenticated user. The /notifications route displays the list of notifications, and the /notifications/{id}/read route marks a notification as read.

Step 5: Create Notification Controller

Next, create a controller to manage the display and marking of notifications. Here is the Artisan command to generate the controller:

php artisan make:controller NotificationController

Code: app/Http/Controllers/NotificationController.php

<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
class NotificationController extends Controller
{
    public function index()
    {
        $notifications = Auth::user()->notifications; // Fetch notifications for the authenticated user
        return view('notifications.index', compact('notifications'));
    }
    public function markAsRead($id)
    {
        $notification = Auth::user()->notifications()->findOrFail($id);
        $notification->markAsRead();
        return back()->with('success', 'Notification marked as read.');
    }
}

This controller handles the logic for displaying and marking notifications as read. The index method fetches all notifications for the authenticated user, while the markAsRead method marks a specific notification as read.

Step 6: Create the Blade View

Now, create a Blade view to display the notifications. This view will show the notifications stored in the database, along with a button to mark them as read.

Code: resources/views/notifications/index.blade.php

@extends('layouts.app')
@section('title', 'Notifications')
@section('content')
<div class="container">
    <h1 class="mt-4">Your Notifications</h1>
    @if (session('success'))
        <div class="alert alert-success">
            {{ session('success') }}
        </div>
    @endif
    <ul class="list-group">
        @forelse ($notifications as $notification)
            <li class="list-group-item">
                <div><strong>{{ $notification->data['message'] }}</strong></div>
                <div><small>Received at: {{ $notification->created_at->diffForHumans() }}</small></div>
                <div class="mt-2">
                    @if (!$notification->read_at)
                        <form action="{{ route('notifications.read', $notification->id) }}" method="POST" class="d-inline">
                            @csrf
                            @method('PATCH')
                            <button type="submit" class="btn btn-sm btn-primary">Mark as Read</button>
                        </form>
                    @else
                        <span class="badge bg-secondary">Already read</span>
                    @endif
               </div>
            </li>
        @empty
            <li class="list-group-item"><p>No notifications found.</p></li>
        @endforelse
    </ul>
</div>
@endsection

This Blade view renders the list of notifications. It shows the message content, the time the notification was received, and a button to mark the notification as read. If the notification has already been read, it displays a “Already read” badge.

Step 7: Test the Implementation

Finally, log in as a user using the Breeze-provided login functionality. Visit the /send-notification route to trigger the notification. Once the notification is sent, you will be redirected to the /notifications route where the notification will be displayed. You can also mark the notification as read.

By following these steps, you’ll successfully implement the Laravel Notification System to deliver notifications via email and store them in the database. It’s a great way to keep users informed and enhance user experience within your Laravel application. If you are looking to build a website that aligns with your needs, get in touch with our Laravel development company.

Advanced Tips and Tricks for Laravel Notifications

Laravel’s notification system is incredibly powerful, and when leveraged to its full potential, it can enhance the user experience in your application. Here are some advanced tips and tricks to help you maximize the effectiveness and performance of your notifications.

Queue Notifications for Better Performance

To ensure better performance and avoid blocking the main thread, you can queue notifications for asynchronous processing. By implementing the ShouldQueue interface in your notification class, you can offload the task of sending notifications to a background job.

use Illuminate\Contracts\Queue\ShouldQueue;
class TaskCompleted extends Notification implements ShouldQueue
{
    // Your notification logic here
}

Make sure to configure your queue driver in the .env file to enable background job processing.

Use Custom Notification Channels

Laravel allows you to create custom notification channels to send notifications through platforms like Slack, Twilio, or any third-party API. By defining a custom channel, you can send notifications to virtually any medium you need.

Real-Time Notifications with Pusher

For real-time updates, combine Laravel notifications with services like Pusher or WebSockets. This allows you to push notifications instantly to users without the need for them to refresh the page.

Notification Filtering

Sometimes you may want to retrieve specific types of notifications, such as unread notifications. You can use scopes to filter notifications and only fetch the ones you need, improving performance and user experience.

$unreadNotifications = Auth::user()->unreadNotifications;

Custom Database Tables

By default, Laravel stores notifications in a standard notifications table. However, you can customize the database structure by defining the viaDatabase() method. This allows you to store additional data or modify the table schema to suit your application’s needs.

By implementing these advanced tips, you can enhance both the performance and flexibility of the Laravel notification system, making it more efficient and customized to your needs.

Need expert assistance with your Laravel project?

FAQs About Laravel Notification System

How to create a notification table in Laravel?
To create a notification table in Laravel, run the command php artisan notifications:table, which will generate a migration for the notifications table. Then, run php artisan migrate to create the table in your database.
What is the difference between mail and notification in Laravel?
In Laravel, Mail is used to send emails, whereas Notifications provide a unified API to send alerts across multiple channels (email, SMS, database, etc.). Notifications are more flexible and can be sent to different mediums at once, while Mail is specific to email delivery.
How to create push notifications in Laravel?
To create push notifications in Laravel, you can use services like Pusher or Firebase Cloud Messaging (FCM). First, integrate the service into your Laravel app, then create a notification class and use the service's API to push notifications to users in real time.

Wrapping Up

Laravel’s Notification System is an essential feature for building applications that keep users informed and engaged. With support for multiple channels like email, SMS, and database, it offers a flexible and efficient way to deliver updates and alerts. Setting up the system requires minimal effort, and advanced features like queuing notifications, creating custom channels, and enabling real-time updates make it even more powerful.

By using these capabilities, developers can create custom notification systems that enhance the user experience and ensure timely communication. Whether for simple alerts or complex real-time interactions, Laravel provides everything needed to implement a reliable notification system.If you are looking to build a real-time website that performs well and is well-designed, hire Laravel developers.

author
Mayur Upadhyay is a tech professional with expertise in Shopify, WordPress, Drupal, Frameworks, jQuery, and more. With a proven track record in web development and eCommerce development.

Leave a comment