Black Friday: the Laravel testing course is $149 instead of $249, through Dec 7. See the course →
logo

How to customize the database notification model

Not documented, but very simple

Joel Clermont
Joel Clermont
2024-07-25

From our daily Laravel tips email. Get the next one in your inbox.

Database notifications are a useful feature if you want to show in-app alerts.

On the same multi-tenant project I talked about yesterday, I wanted to customize the database notification model, so I could set the multi-tenancy connection properly.

This should be pretty simple. Laravel is very extensible, but I saw nothing in the documentation about how to do this.

After digging in a little, I realized it was a simple two-step process:

  1. Create your new model class, and extend Illuminate\Notifications\DatabaseNotification from the framework.
  2. In your notifiable model, for example App\Models\User, now you just need to override the notifications() relationship to use your notification model instead of the one from the framework.

It looks like this:

public function notifications()
{
    return $this->morphMany(App\Models\DatabaseNotification::class, 'notifiable')->latest();
}

This is a pretty specific use case, but maybe it will help you if you ever need to customize the database notification model in your project.

Here to help,

Joel

P.S. Have a question about how to customize something else in Laravel? Join the Mastering Laravel community and ask away!

Want a tip like this in your inbox every weekday?

Each one takes less than 2 minutes to read. Join 4,000+ Laravel developers who already get them.

email
No spam. Only real-world advice.
Toss a coin in the jar if you found this helpful.