Laravel 通知存储附加 ID 字段

所以我设置了 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'

        ];

    }

}

所以是的,我可以将它存储在数据中,但是如果我想通过“项目”而不是“用户”或“通知”专门清除通知怎么办。


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


那么无论如何要project_id在通知中插入它吗?


桃花长相依
浏览 171回答 1
1回答

慕容3067478

您可以创建一个观察者来自动更新该字段。NotificationObserver.phpnamespace App\Observers;class NotificationObserver{&nbsp; &nbsp; public function creating($notification)&nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; $notification->project_id = $notification->data['project_id'] ?? 0;&nbsp; &nbsp; }}事件服务提供者.phpuse App\Observers\NotificationObserver;use Illuminate\Notifications\DatabaseNotification;class EventServiceProvider extends ServiceProvider{&nbsp; &nbsp; public function boot()&nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; parent::boot();&nbsp; &nbsp; &nbsp; &nbsp; DatabaseNotification::observe(NotificationObserver::class);&nbsp; &nbsp; }}您应该能够使用默认模型访问表以执行操作。DatabaseNotification::where('project_id', 11)->delete();
打开App,查看更多内容
随时随地看视频慕课网APP