Laravel 通知存储附加 ID 字段

Laravel Notification Store Additional ID Fields

所以我有 Laravel 通知设置,它工作得很好。

但是,我扩展了迁移以包含一个额外的 id 字段:

$table->integer('project_id')->unsigned()->nullable()->index();

问题是,我不知道如何实际设置 project_id 字段。我的通知如下所示:

<?php

namespace App\Notifications\Project;

use App\Models\Project;
use App\Notifications\Notification;

class ReadyNotification extends Notification
{
    protected $project;

    public function __construct(Project $project)
    {
        $this->project = $project;
    }

    public function toArray($notifiable)
    {
        return [
            'project_id' => $this->project->id,
            'name' => $this->project->full_name,
            'updated_at' => $this->project->updated_at,
            'action' => 'project-ready'
        ];
    }
}

是的,我可以将它存储在数据中,但是如果我想通过 "project" 而不是 "user" 或 "notification" 来清除通知怎么办?

例如,如果他们删除了该项目,我希望清除它的通知,但除非我在 data 列上进行通配符搜索,否则无法访问它。

所以有没有办法在通知中插入 project_id

您可以创建一个观察者来自动更新字段。

NotificationObserver.php

namespace App\Observers;

class NotificationObserver
{
    public function creating($notification)
    {
        $notification->project_id = $notification->data['project_id'] ?? 0;
    }
}

EventServiceProvider.php

use App\Observers\NotificationObserver;
use Illuminate\Notifications\DatabaseNotification;

class EventServiceProvider extends ServiceProvider
{
    public function boot()
    {
        parent::boot();

        DatabaseNotification::observe(NotificationObserver::class);
    }
}

并且您应该能够使用默认模型访问 table 以执行操作。

DatabaseNotification::where('project_id', 11)->delete();