How to change default notification table name in Laravel

Viewed 3906

I want to change notification table name, so I changed the migration file:

php artisan notification:table

Schema::create('member_notifications', function (Blueprint $table) {
      $table->uuid('id')->primary();
      $table->string('type');
      $table->morphs('notifiable');
      $table->text('data');
      $table->timestamp('read_at')->nullable();
      $table->timestamps();
});

And trying to use $table in Notification class :

protected $table = 'member_notifications';

But when I trying to store notification in database I get this error:

SQLSTATE[42P01]: Undefined table: 7 ERROR: relation "notifications" does not exist
2 Answers

If you want to change default notifications table to your custom table, you should do 3 things:

  1. Change table name in migration file to member_notifications. Run migration.
  2. Create your model, for example DatabaseMemberNotification. Extend it from Illuminate\Notifications\DatabaseNotification and override property

    protected $table = 'member_notifications';
    
  3. In default User model add this function:

    public function notifications()
    {
        return $this->morphMany(DatabaseMemberNotification::class, 'notifiable')->orderBy('created_at', 'desc');
    }
    

    Actually it will override notifications() method in HasDatabaseNotifications trait.

    Note: first parameter should be your new model class.

Related