Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Laravel change Connection for Notifications table

I am implementing Laravel 5.3 Notifications at the moment which is working very nice.

At the moment I am using 'email' as a notifications channel but I want to add 'database' too. I am using different databases/connections for languages and want to store the notifications in a central database / Connection.

How do I use a different database connection for notifications?

I already tried creating a Notifications model but that did not work:

namespace App;

use Illuminate\Database\Eloquent\Model;

class Notifications extends Model
{
    protected $connection = 'system';
}
like image 310
klaaz Avatar asked Mar 11 '23 05:03

klaaz


1 Answers

Hackish solution. But tried and tested on a MongoDB connection.

What needs to be modified;

  1. The Notifiable trait
  2. The DatabaseNotification model
  3. Optionally (nothing changes if you are using mysql) modify the HasNotifications trait
  4. Modify the DatabaseNotificationCollection.Again this is useful for a non-mysql connection

Step One : Create a custom Notifiable Trait

Copy the contents from Illuminate\Notifications\Notifiable and create a new file in your custom path...say App\Overrides\Notifications\Notifiable.

Your file will feature two changes...the namespace and you have to load the RoutesNotifications trait since we are not copying it over.

<?php

namespace App\Overrides\Notifications;

use use Illuminate\Notifications\RoutesNotifications;

trait Notifiable{
 //The rest of the code remains
}

Step Two : Create a custom DatabaseNotification model

Follow the same procedure as above and copy the contents of the Illuminate\Notifications\DatabaseNotification file to the custom path that we created above...App\Overrides\Notification\DatabaseNotification

This is a standard Eloquent model and the connection change actually happens here

<?php

namespace App\Overrides\Notification;

//Use this if on mongodb.otherwise use to Illuminate\Database\Eloquent\Model
use Jenssegers\Mongodb\Eloquent\Model;
use Illuminate\Notifications\DatabaseNotificationCollection;

class DatabaseNotification extends Model
{
  protected $connection = 'YOUR_CONNECTION_NAME_GOES HERE'; 
}

As of this point this should work if you are on a mysql connection.

To try this out change the Notifiable trait on the user model to use App\Overrides\Notifications\Notifiable. The notifications will use the connection you specified.

Users of MongoDB will have to take extra steps since the most popular driver I know of does not yet support MorphMany relations which are put to use for Laravel notifications.

Since that is not the asked question we leave it at that :-)

like image 113
Bernard Nandwa Avatar answered Apr 08 '23 14:04

Bernard Nandwa