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:
- Create your new model class, and extend
Illuminate\Notifications\DatabaseNotification
from the framework. - In your notifiable model, for example
App\Models\User
, now you just need to override thenotifications()
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!