Laravel: customize or extend notifications - database model

前端 未结 5 1392
我在风中等你
我在风中等你 2020-12-03 08:11

IMHO, the current Database channel for saving notifications in Laravel is really bad design:

  • You can\'t use foreign key cascades on items for cleaning up noti
5条回答
  •  春和景丽
    2020-12-03 09:08

    Create and use your own Notification model and Notifiable trait and then use your own Notifiable trait in your (User) models.

    App\Notifiable.php:

    namespace App;
    
    use Illuminate\Notifications\Notifiable as BaseNotifiable;
    
    trait Notifiable
    {
        use BaseNotifiable;
    
        /**
         * Get the entity's notifications.
         */
        public function notifications()
        {
            return $this->morphMany(Notification::class, 'notifiable')
                                ->orderBy('created_at', 'desc');
        }
    }
    

    App\Notification.php:

    namespace App;
    
    use Illuminate\Notifications\DatabaseNotification;
    
    class Notification extends DatabaseNotification
    {
        // ...
    }
    

    App\User.php:

    namespace App;
    
    use Illuminate\Foundation\Auth\User as Authenticatable;
    
    class User extends Authenticatable
    {
        use Notifiable;
    
        // ...
    }
    

提交回复
热议问题