Customize your database notification and database channel in Laravel

Mohamed Amine ALOUINI
2 min readJan 19, 2020

This tutorial was made using Laravel 6.x

Laravel provides a built in support to send notifications across multiple channels, like email, database, Slack, SMS… etc. In this tutorial, I will explain how we can customize both, the channel and the Notification Database implementation to fit our needs.

Customize your Laravel Database Channel

I tried to define the Laravel database in the simplest way, but I found that Laravel documentation is very simple :

The database notification channel stores the notification information in a database table. This table will contain information such as the notification type as well as custom JSON data that describes the notification.

Let’s imagine that in our application we need to implement the Database notification, for that we need a notifications table that you can create its migration via :
php artisan notifications:table

A new migration will be added to the your migrations directory:

As we can see, we have defined columns in the notifications table, but in some projects, developers may need to add other custom fields, and they want to fill them.

For example, I was working on a multi tenant application and the notifications table was shared between all tenants, so I wanted to add a ‘tenant_id’ field.

Some developers may want to add this information to the ‘data’ field, but this will make it harder to fetch notifications since the data field is a JSON.

So how to fill the custom field(s)?

For that, We create a new DatabaseChannel class under app/channels/DatabaseChannel.php

This class will extend Illuminate\Notifications\Channels\DatabaseChannel and override the method buildPayload

PS: This was my BaseNotification class

Customize your Laravel Database Notification

For some case, your may need to use a different connection to store your Database Notification.

For that, We create a new DatabaseNotification model app/DatabaseNotification.php

This class will extend Illuminate\Notifications\DatabaseNotification

In the new model you can tell laravel which connection, it should use via the protected attribute $connection or any other customization related to eloquent.

How to ensure that Laravel will use our new Classes instead of its built in ones?

Here comes the hardest part.
No I’m kidding.

One of the main features in Laravel is ‘service container”, this tool help us manage class dependencies and perform dependency injection easily.

Read more about it here.

We should update the boot method under app/Providers/AppServiceProvider.php

Et voilà

Congrats you just customized your Database notification.

Please do not forget to clap and share the article between Laravel developers and contact me in case you need any help or the article is not clear.



Mohamed Amine ALOUINI

A JS developer | Technology enthusiast | Dockerize it and Ship it | AWS | From 🇹🇳