logo
podcast Podcast
get help Get Unstuck

How to customize the database notification model

Not documented, but very simple

Joel Clermont
Joel Clermont
2024-07-25

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!

Toss a coin in the jar if you found this helpful.
Want a tip like this in your inbox every weekday? Sign up below 👇🏼
email
No spam. Only real-world advice you can use.