Adding column to Database Notifications table
When you need additional scope on notifications
Suppose your user can belong to many teams, and they have the ability to switch teams, you, like me, may want to allow the user to have unread notifications only for the team that they are currently in.
A similar situation may exist for multi-tenant applications where the same user can be a member of different tenants.
You may find that you need an additional column on the notifications table that you can then later filter with a global scope.
This article: https://www.ystash.com/blog/extra-columns-with-laravel-database-notifications/ suggests creating a new database notification channel.
The approach presented here is simpler as it only involves listening to the Notification Eloquent model creating event using an observer.

Add your additional column to the notifications table

This is fairly straightforward, just a regular migration targeting the notifications table
1
public function up()
2
{
3
Schema::table('notifications', function (Blueprint $table) {
4
$table->foreignId('organisation_id');
5
});
6
}
Copied!

Create an observer

If you don't already have it, create app\Observers table
Create new file NotificationObserver.php
app\Observers\NotificationObserver.php
1
<?php
2
3
namespace App\Observers;
4
5
class NotificationObserver
6
{
7
public function creating($model)
8
{
9
// here set the column data for your new column
10
}
11
12
}
13
Copied!

Add Observer to AppServiceProvider

In the boot() method of Providers/AppServiceProvider
1
public function boot()
2
{
3
DatabaseNotification::observe(NotificationObserver::class);
4
}
Copied!
Thats it! when your database notification is created, your additional data will be added
Last modified 30d ago