Передача данных в уведомление в laravel - PullRequest
1 голос
/ 30 января 2020

Некоторое время был озадачен тем, как передать две переменные в уведомление и включить ли это уведомление в действие, которое содержит маршрут с токеном. Сценарий использования состоит в том, что мое приложение позволяет пользователям (называемым здесь советниками) предоставлять доступ другим пользователям. Если добавленные пользователи еще не зарегистрированы, их учетные записи будут созданы, и они получат электронное письмо с токеном для завершения своей регистрации.

В моем AddAdvisorsController есть следующее:

 else {


        $newadvisor = Advisor::create($data);
        $newadvisor->save();

        $newadvisorID = $newadvisor->id;
        $newAdvisorEmail = $newadvisor->email;

        //create a token
        $token = Str::random(60);
        //email advisor and pass $token variable to notification
        $newadvisor->notify(new NewAdvisorNotification($token, $newAdvisorEmail));

В моем NewAdvisorNotification указано следующее:

<?php

namespace App\Notifications;

use Illuminate\Bus\Queueable;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Notifications\Messages\MailMessage;
use Illuminate\Notifications\Notification;

class NewAdvisorNotification extends Notification
{
 use Queueable;

public $token;



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


}

/**
 * Get the notification's delivery channels.
 *
 * @param  mixed  $notifiable
 * @return array
 */
public function via($notifiable)
{
    return ['mail'];
}

/**
 * Get the mail representation of the notification.
 *
 * @param  mixed  $notifiable
 * @return \Illuminate\Notifications\Messages\MailMessage
 */
public function toMail($notifiable)
{
    return (new MailMessage)
                ->line('You are receiving this email because we received a new account request for your email.')
                ->action('Notification Action', route('new.advisor', [$this->token, $this->newAdvisorEmail]))
                // ->action('Notification Action', route('advisor/new-account/{{ $token }}/{newAdvisorEmail}'))
                ->line('If you did not request a password reset, no further action is required.');
}

/**
 * Get the array representation of the notification.
 *
 * @param  mixed  $notifiable
 * @return array
 */
public function toArray($notifiable)
{
    return [
        //
    ];
}

}

Новый пользователь правильно создается в базе данных, но я получаю сообщение об ошибке:

Отсутствует обязательные параметры для [Route: update.advisor] [URI: советник / новая учетная запись / {токен} / {newAdvisorEmail}]. (Представление: C: \ xampp \ htdocs \ HealthHub \ resources \ views \ auth \ new-account \ advisor-new-account.blade. php)

У меня есть следующие маршруты:

    Route::get('/advisor/new-account/{token}/{newAdvisorEmail}', 'NewAdvisorController@showNewAccountForm')->name('new.advisor');
Route::post('/advisor/new-account/{token}/{newAdvisorEmail}', 'NewAdvisorController@updateNewAccount')->name('update.advisor');

});

Я думаю, что в моем коде есть ошибки с этой строкой:

                ->action('Notification Action', route('new.advisor', [$this->token, $this->newAdvisorEmail]))

Однако я не уверен, как это исправить

1 Ответ

0 голосов
/ 30 января 2020

В вашей ошибке четко указано, что вам не хватает параметров для вашего маршрута. Способ задания параметров маршрута - по имени, поэтому объявите ассоциированный массив с именем параметра маршрута в качестве ключа.

 ->action('Notification Action', route('new.advisor', ['token' => $this->token, 'newAdvisorEmail' => $this->newAdvisorEmail,]))
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...