Laravel Уведомление о том, как установить пользовательское значение столбца - PullRequest
0 голосов
/ 06 мая 2019

Я использовал команду 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 голосов
/ 06 мая 2019

Вы должны использовать метод 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
        ];
    }

final toArray вывод сериализуется в столбец data таблицы notifications.

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...