Laravel Notification如何设置自定义列值

时间:2019-05-06 03:14:25

标签: php laravel

我在通知迁移中使用了php artisan notification:table命令创建了一个名为user_id的自定义列。如何设置自定义列user_id的值?

Schema::create('notifications', function (Blueprint $table) {
    $table->uuid('id')->primary();
    $table->unsignedBigInteger('user_id');
    $table->string('type');
    $table->morphs('notifiable', 50);
    $table->text('data');
    $table->timestamp('read_at')->nullable();
    $table->timestamps();
    $table->foreign('user_id')->references('id')->on('users')->onDelete('cascade')->onUpdate("cascade");
});

在此函数中,我发送了通知,但引发了错误。 user_id列没有默认值

public function saveUser($formdata)
{
    $password = $formdata['password'];
    $securePassword = Hash::make($password);

    $user = User::create(array_merge($formdata, ['password' => $securePassword]));
    $admin = User::where('type', 'admin')->first();
    $letter = collect([
        'title' => $user->name.' New User Registered in your Portal',
    ]);

    Notification::send($admin, new DatabaseNotification($letter));

    return $user;
} 

请帮助我弄清楚如何设置user_id值。

1 个答案:

答案 0 :(得分:0)

您应该使用toDatabasetoArray方法来保存任何其他数据。另外,您无需更改通知迁移。 您应该在$letter内构造DatabaseNotification变量,例如:

public function saveUser($formdata)
{
    $password = $formdata['password'];
    $securePassword = Hash::make($password);

    $user = User::create(array_merge($formdata, ['password' => $securePassword]));
    $admin = User::where('type', 'admin')->first();
    // $letter = collect([
    //     'title' => $user->name.' New User Registered in your Portal',
    // ]);

    // This syntax or below.
    // Notification::send($admin, new DatabaseNotification($user, $message));

    // Make sure you added `use Notifiable` trait in your `User` model
    $admin->notify(new DatabaseNotification($user, $message));

    return $user;
} 

然后使用您的toArraytoDatabase方法:

    protected $message;
    protected $user;

    /**
     * Create a new notification instance.
     *
     * @return void
     */
    public function __construct($message, User $user)
    {
        $this->message = $message;
        $this->user = $user;
    }

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

最终的toArray输出被序列化到data表的notifications列中。