Notifications
- Introduction
- Complete Example: On-Demand Notification
- Generating Notifications
- Sending Notifications
- Mail Notifications
- Database Notifications
- Broadcast Notifications
- Custom Channels
- Testing Notifications
Introduction
A notification is a short message sent over one or more channels: mail (Mail), database (a row in the notifications table, for an in-app list), and broadcast (pushed to the browser with SignalR). Each notification is a class, like in Laravel.
Generating Notifications
dotblaze make:notification InvoicePaid # queued
dotblaze make:notification InvoicePaid --sync # sent immediatelyNotifications live in app/Notifications. From the sample app:
using SampleApp.Models;
namespace SampleApp.Notifications;
public class PostPublished : Notification, IShouldQueue
{
public required Post Post { get; init; }
public override string[] Via(object notifiable) => ["mail", "database", "broadcast"];
public override MailMessage ToMail(object notifiable) => new MailMessage()
.Subject($"Your post \"{Post.Title}\" is live")
.View("mail/post-published", Post);
public override object ToArray(object notifiable) => new
{
postId = Post.Id,
title = Post.Title,
url = URL.Route("posts.show", new { post = Post.Id }),
};
}Data goes in public properties (not a primary constructor), so a queued notification can be serialized like a job; models are stored by id and fetched again.
Sending Notifications
await user.Notify(new PostPublished { Post = post });
await Notification.Send(users, new PostPublished { Post = post }); // one or many notifiables
await Notification.SendNow(user, new PostPublished { Post = post }); // skip the queueThe Notifiable Interface
A model that receives notifications implements INotifiable:
public class User : Model<User>, IAuthenticatable, INotifiable { ... }RouteNotificationFor(channel) tells each channel where to deliver: the Email property for mail, the model itself for database, and the SignalR group "User.{Id}" for broadcast. Implement it on your model to change that:
public object? RouteNotificationFor(string channel, Notification? notification = null) => channel switch
{
"mail" => BillingEmail,
"database" => this,
"broadcast" => $"User.{Id}",
_ => null,
};A notifiable without a mail address is skipped by the mail channel.
Specifying Delivery Channels
Via(notifiable) returns the channel names and can decide per notifiable:
public override string[] Via(object notifiable) =>
notifiable is User { WantsEmail: true } ? ["mail", "database"] : ["database"];Queueing Notifications
Add IShouldQueue to send through the queue. Like Laravel, one job is pushed per notifiable and channel, so a failing channel is retried on its own; all jobs for one notifiable share the notification Id. Override Queue or Delay to choose the queue or wait before sending:
public override string? Queue => "notifications";
public override TimeSpan? Delay => TimeSpan.FromMinutes(5);On-Demand Notifications
To notify an address that is not a model:
await Notification.Route("mail", "ops@example.com").Notify(new ServerDown { Host = "web-1" });The database channel is not available on demand.
Mail Notifications
ToMail(notifiable) returns a MailMessage: lines and a button rendered with the built-in template, or a Razor view. Messages are sent through the default mailer unless the message calls Mailer(...).
Database Notifications
Prerequisites
The database channel stores rows in a notifications table. The application template includes this migration:
Schema.Create("notifications", t =>
{
t.String("id", 36);
t.String("type");
t.String("notifiable_type");
t.String("notifiable_id", 64);
t.Text("data");
t.DateTime("read_at").Nullable();
t.Timestamps();
t.Primary("id");
t.Index("notifiable_type", "notifiable_id");
});ToDatabase(notifiable) (by default ToArray) is stored as JSON in data. type is DatabaseType (default: the class name), notifiable_type the model's class name, and notifiable_id its key as text.
Accessing the Notifications
Rows are DatabaseNotification models. The notifiable gets query methods, newest first:
var all = await user.Notifications().Get();
var unread = await user.UnreadNotifications().Count();
var read = await user.ReadNotifications().Paginate(20);
foreach (var n in all)
{
var title = n.Get<string>("title"); // a value from data
var data = n.DataAs<PostPublishedData>(); // or the whole object
}Marking Notifications as Read
await notification.MarkAsRead();
await notification.MarkAsUnread();
await user.MarkNotificationsAsRead(); // all unread ones, returns the countBroadcast Notifications
The broadcast channel pushes the notification to the user's browser through a SignalR hub mapped at /broadcasting (config broadcasting.path). A logged-in user's connection joins the group "{UserType}.{id}", and each notification arrives as a notification event with { id, type, data }, where data is ToBroadcast(notifiable) (by default ToArray).
WARNING
Connections live in the web process. Without a backplane, a notification broadcast from a separate dotblaze queue:work process (or another web server) reaches no browser, and a warning is logged. Set driver = "redis" in config/Broadcasting.cs to use the Redis backplane, or run queued broadcast notifications with the in-app worker (worker = true in config/Queue.cs).
Listening in the Browser
Use DotBlaze's broadcasting client; the login cookie authenticates the connection. The sample layout forwards each notification to its live notification bell:
<script src="~/build/signalr.js"></script>
@Broadcast.Scripts()
<script>
window.Echo = new DotBlazeEcho();
Echo.notification(n => Live.dispatch("notification-received", n));
</script>The sample's npm run build copies signalr.min.js from node_modules/@microsoft/signalr to wwwroot/build.
Custom Channels
Implement INotificationChannel and register it under the name used in Via:
public class SmsChannel(ISmsClient sms) : INotificationChannel
{
public Task Send(object notifiable, Notification notification) =>
sms.Send(((User)notifiable).Phone, ((InvoicePaid)notification).ToSms());
}
// AppServiceProvider.Register
services.AddNotificationChannel<SmsChannel>("sms");Testing Notifications
Notification.Fake() records notifications instead of sending (or queueing) them:
var notifications = Notification.Fake();
await user.Notify(new OrderShipped { Order = "X-9" });
notifications.AssertSentTo<OrderShipped>(user, n => n.Order == "X-9");
notifications.AssertNotSentTo<OrderShipped>(otherUser);
notifications.AssertCount(1);
// AssertNothingSent() would fail here because a notification was sent.
// AssertSentOnDemand requires a separate Notification.Route(...).Notify(...) call.A notifiable matches when it is the same instance or the same type with the same key, so a model fetched again still counts. See Fakes for the rules every fake follows.
Complete Example: On-Demand Notification
No user model is required for this Blog command:
// app/Commands/NotificationDemo.cs
using DotBlaze;
namespace Blog.Commands;
public class DocumentationNotice : Notification
{
public override string[] Via(object notifiable) => ["mail"];
public override MailMessage ToMail(object notifiable) => new MailMessage()
.Subject("Documentation ready").Line("Your example is ready to read.");
}
public class NotificationDemo : Command
{
public override string Signature => "demo:notification";
public override async Task<int> Handle()
{
var notifications = Notification.Fake();
await Notification.Route("mail", "reader@example.test")
.Notify(new DocumentationNotice());
notifications.AssertSentOnDemand<DocumentationNotice>("mail", "reader@example.test");
notifications.AssertCount(1);
Line("One on-demand notification recorded.");
return 0;
}
}Run dotblaze demo:notification. The fake suppresses all delivery channels. For database notifications, use a saved INotifiable model and the template's migrated notifications table; an arbitrary email address cannot own a database notification. The sample notification list demonstrates listing and marking notifications through the current user's owner-scoped query.