为了账号安全,请及时绑定邮箱和手机立即绑定

Laravel Notification如何设置自定义列值

Laravel Notification如何设置自定义列值

PHP
动漫人物 2021-05-14 17:13:41
我使用该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 回答

?
慕桂英4014372

TA贡献1871条经验 获得超13个赞

您应该使用toDatabase或toArray方法来保存任何其他数据。另外,您无需更改通知迁移。您应该$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;

然后在您的toArray或toDatabase方法中:


    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。


查看完整回答
反对 回复 2021-05-28
  • 1 回答
  • 0 关注
  • 229 浏览

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信