How to build a notification system with Laravel
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.
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!

Hot AI Tools

Undress AI Tool
Undress images for free

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

ArtGPT
AI image generator for creative art from text prompts.

Stock Market GPT
AI powered investment research for smarter decisions

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

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

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

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

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

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

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

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.

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.
