【问题标题】:Laravel: Notifications table with custom columnLaravel:带有自定义列的通知表
【发布时间】:2021-07-17 15:20:45
【问题描述】:

我使用的是 Laravel 默认的 notifications 系统。但是,我需要在notifications 表中添加一个额外的列来检查用户是否已经拥有相同的未读通知。

例如:如果用户的个人资料不完整,则每次登录时都会提醒他/她,直到个人资料完成。但是如果之前生成的通知仍然是unread,则不会生成新的notification

表格:通知

default_fields notify ...
... profile_incomplete ...
... password_change_overdue ...

通知类

class NotifyToCompleteProfileNotification extends Notification
{
    public function __construct() 
    {
        $this->notify = 'profile_incomplete';
    }

    /**
     * Get the notification's delivery channels.
     *
     * @param  mixed  $notifiable
     * @return array
     */
    public function via($notifiable)
    {
        return ['database'];
    }

    /**
     * Get the array representation of the notification.
     *
     * @param  mixed  $notifiable
     * @return array
     */
    public function toArray($notifiable)
    {
        return [
            'data' => '...',
        ];
    }
}

【问题讨论】:

  • 默认的 Laravel 通知系统已经有 type 列携带使用的通知类名。
  • 是的,我知道。这只是一个例子。
  • 知道了,看看我的答案。

标签: php laravel notifications customization


【解决方案1】:

您可以使用自定义通知渠道来实现这一点。假设您想在通知中添加一个group 字段。首先将此字段添加到表中,然后制作文件GroupedDbChannel.php

namespace App\Notifications;


use Illuminate\Notifications\Notification;

class GroupedDbChannel
{
    public function send($notifiable, Notification $notification)
    {
        $data = $notification->toDatabase($notifiable);
        return $notifiable->routeNotificationFor('database')->create([
            'id' => $notification->id,
            'group' => $notification->group,
            'type' => get_class($notification),
            'data' => $data,
            'read_at' => null,
        ]);
    }
}

接下来,您需要为通知定义自定义组和通道:

namespace App\Notifications;

use Illuminate\Notifications\Notification;

class TestNotification extends Notification {

    /*
     * Here you define additional value that will
     * be used in custom notification channel.
     */
    public string $group = 'incomplete-profile';
    

    public function via($notifiable) {
        return [GroupedDbChannel::class];
    }

    public function toArray($notifiable) {
        return [
            // notification data
        ];
    }

    /*
     * It's important to define toDatabase method due 
     * it's used in notification channel. Of course, 
     * you can change it in GroupedDbChannel.
     */
    public function toDatabase($notifiable): array
    {
        return $this->toArray($notifiable);
    }

}

它已经完成了。使用通知作为标准。

$user->notify(new TestNotification());

现在,值 incomplete-profile$group 字段转到 notifications 表到 group 列。

【讨论】:

  • 好的,我试试这个
猜你喜欢
  • 2018-12-15
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-02-09
  • 2014-04-15
  • 2020-03-21
相关资源
最近更新 更多