Table of Contents
1. Set Up the Database for Notifications
2. Create a Notification Class
3. Send the Notification
4. Display Notifications in the Frontend
5. Real-Time Notifications with Broadcasting (Optional)
6. Customize Notification Behavior
Summary
Home PHP Framework Laravel How to build a notification system with Laravel

How to build a notification system with Laravel

Sep 01, 2025 am 08:15 AM

Run php artisan notifications:table and migrate to set up the database. 2. Create a notification class using php artisan make:notification NewMessageReceived and define channels in the via method, data in toDatabase, and real-time broadcasting in toBroadcast. 3. Send notifications via $user->notify(new NewMessageReceived($message)) or use the Notification facade for multiple users. 4. Fetch notifications using auth()->user()->notifications or unreadNotifications, and mark them as read with markAsRead(). 5. For real-time updates, configure broadcasting with Pusher or Laravel Echo and listen on the private channel for notifications. 6. Customize behavior by conditionally returning channels, modifying the database schema, or handling soft deletes. Laravel’s notification system allows seamless delivery across multiple channels with a clean, consistent API.

How to build a notification system with Laravel

Building a notification system in Laravel is straightforward thanks to its built-in notification features. Laravel provides a clean, flexible way to send notifications across multiple channels like database, email, SMS, and more. Here's how to set up a complete notification system using Laravel's native tools.


1. Set Up the Database for Notifications

First, Laravel uses a notifications table to store database notifications. Generate the migration:

php artisan notifications:table

Then run the migration:

php artisan migrate

This creates a notifications table with fields like id, type, notifiable_id, notifiable_type, data, and read_at.


2. Create a Notification Class

Use Artisan to generate a notification:

php artisan make:notification NewMessageReceived

This creates a class in app/Notifications/NewMessageReceived.php. Edit it to define how the notification should be delivered:

<?php

namespace App\Notifications;

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

class NewMessageReceived extends Notification implements ShouldQueue
{
    use Queueable;

    public $message;

    public function __construct($message)
    {
        $this->message = $message;
    }

    // Define which channels to use: database, mail, broadcast, etc.
    public function via($notifiable)
    {
        return ['database', 'broadcast']; // Also add 'mail' if needed
    }

    // Store notification in the database
    public function toDatabase($notifiable)
    {
        return [
            'message' => $this->message,
            'sender_id' => auth()->id(),
            'sender_name' => auth()->user()->name,
            'url' => url('/messages/' . $this->message->id)
        ];
    }

    // Optional: Broadcast via Laravel Echo (for real-time UI updates)
    public function toBroadcast($notifiable)
    {
        return new BroadcastMessage([
            'message' => $this->message,
            'sender_name' => auth()->user()->name,
            'created_at' => now()->toDateTimeString()
        ]);
    }
}

Note: Implement ShouldQueue to ensure notifications are sent asynchronously for better performance.


3. Send the Notification

You can send notifications to a user using the notify() method.

use App\Notifications\NewMessageReceived;
use App\Models\User;

$user = User::find(1); // Recipient
$message = // your message model or data

$user->notify(new NewMessageReceived($message));

Alternatively, use the Notification facade to send to multiple users:

use Illuminate\Support\Facades\Notification;

Notification::send(User::all(), new NewMessageReceived($message));

4. Display Notifications in the Frontend

Fetch unread notifications from the controller:

public function getNotifications()
{
    return auth()->user()->notifications;
}

public function getUnreadNotifications()
{
    return auth()->user()->unreadNotifications;
}

Mark a notification as read:

$notification = auth()->user()->notifications()->find($id);
$notification->markAsRead();

Or mark all as read:

auth()->user()->markAsRead();

In Blade templates:

<ul>
    @foreach (auth()->user()->unreadNotifications as $notification)
        <li>{{ $notification->data['message'] }} from {{ $notification->data['sender_name'] }}</li>
    @endforeach
</ul>

5. Real-Time Notifications with Broadcasting (Optional)

To show real-time notifications:

  • Set up broadcasting (e.g., Pusher, Redis Laravel Echo Server).
  • Update toBroadcast() in the notification.
  • Listen in JavaScript:
import Echo from 'laravel-echo';

window.Echo.private(`App.Models.User.${userId}`)
    .notification((notification) => {
        console.log(notification.message);
        // Update UI: add to notification dropdown
    });

Ensure the user model is correctly resolved in broadcasting (check config/broadcasting.php and authentication).


6. Customize Notification Behavior

  • Conditional Channels: Return different channels based on logic:
public function via($notifiable)
{
    $channels = ['database'];

    if ($notifiable->email_notifications) {
        $channels[] = 'mail';
    }

    return $channels;
}
  • Custom Database Schema: Modify the migration to add extra fields like type, icon, etc.
  • Soft Deletes: Notifications are soft-deleted by default. Use forceDelete() to remove permanently.

Summary

Laravel’s notification system is powerful and easy to use. Key steps:

  • Run notifications:table migration
  • Create notification classes with via, toDatabase, etc.
  • Send notifications using $user->notify()
  • Fetch and display in views
  • Add broadcasting for real-time updates

With this setup, you can handle alerts, messages, reminders, and more — all through a consistent API. Basically just configure, send, and display.

The above is the detailed content of How to build a notification system with Laravel. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undress AI Tool

Undress AI Tool

Undress images for free

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

ArtGPT

ArtGPT

AI image generator for creative art from text prompts.

Stock Market GPT

Stock Market GPT

AI powered investment research for smarter decisions

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

How to log messages to a file in Laravel? How to log messages to a file in Laravel? Sep 21, 2025 am 06:04 AM

LaravelusesMonologtologmessagesviatheLogfacade,withdefaultlogsstoredinstorage/logs/laravel.log.Configurechannelsinconfig/logging.phptocontroloutput;thedefaultstackchannelaggregatesmultiplehandlerslikesingle,whichwritestoafile.UseLog::info(),Log::warn

How to authenticate an API in Laravel How to authenticate an API in Laravel Sep 18, 2025 am 12:26 AM

InstallLaravelSanctumviaComposerandpublishitsfiles,thenrunmigrations.2.AddtheHasApiTokenstraittotheUsermodel.3.Definelogin,logout,anduserroutesinapi.php,usingSanctum’sauth:sanctummiddleware.4.ProtectAPIroutesbyapplyingtheauth:sanctummiddleware.5.Incl

How to write a feature test in Laravel with Pest? How to write a feature test in Laravel with Pest? Sep 16, 2025 am 06:12 AM

InstallPestviaComposerandinitializeitinLaraveltosetuptesting.2.Createafeaturetestintests/Featuretovalidateuser-facinginteractionslikeHTTPrequestsanddatabasechangesusingPest’s简洁syntax.

How to implement API authentication with Laravel Sanctum? How to implement API authentication with Laravel Sanctum? Sep 19, 2025 am 04:08 AM

ToimplementAPIauthenticationwithLaravelSanctum,youneedtosetuptoken-basedauthenticationthatallowsSPAs,mobileapps,andthird-partyservicestosecurelyaccessyourAPI.SanctumprovidesalightweightapproachbyissuingAPItokensthatcan

How to use the hasManyThrough relationship in Laravel? How to use the hasManyThrough relationship in Laravel? Sep 17, 2025 am 06:38 AM

ACountrycanaccessallPoststhroughUsersusinghasManyThrough.Forexample,withcountries,users,andpoststableslinkedbyforeignkeys,theCountrymodeldefinesahasManyThroughrelationshiptoPostviaUser,enablingefficientindirectdataretrievalacrosstwoone-to-manyrelatio

How to create a full-text search in Laravel? How to create a full-text search in Laravel? Sep 16, 2025 am 03:42 AM

Toimplementfull-textsearchinLaravel,firstaddafull-textindexinthemigrationusing$table->fullText(['title','content']);thenusewhereFullText(['title','content'],$query)inqueriesforefficientsearching;encapsulatelogicinamodelscopeforreusabilityandfallba

How to use route resource controllers in Laravel? How to use route resource controllers in Laravel? Sep 24, 2025 am 05:05 AM

Laravel resource controller quickly processes CRUD operations through RESTful routing, uses the Artisan command to generate controllers and register resource routes, and can create all standard routes in a single line of code, which supports restriction of actions, adding middleware and naming, and combines routing model binding to automatically parse parameters, improve development efficiency and keep the code structure clear.

How to redirect a user in a Laravel controller? How to redirect a user in a Laravel controller? Sep 21, 2025 am 05:26 AM

Use the redirect() helper function to realize redirection in the Laravel controller, such as redirect()->route('home') to jump to the named route, redirect('/dashboard') to the specified URL, redirect()->back() returns to the previous page, and use withInput() to retain form data and with() to pass session messages. It is recommended to use named routes to improve maintainability.

See all articles