0

I am trying to get the token from ConfirmUserToken and attach it to the URL in the notification. I am trying to create a custom validation in laravel. When I used $notifiable->token, it gives me no result. How can I access the token?

RegisterController

foreach ($users as $u) {
    $cutoken = ConfirmUserToken::create([
        'user_id' => $u->id,
        'concerned_user' => $user->id,
        'token' => Hash::make(now()),
    ]);
    $cutoken->user()->associate($u);
}

Notification::send($users, new ConfirmUser());

ConfirmUserNotification

public function toMail($notifiable)
{
    $confirmUrl = url("confirmUser/{$notifiable->id}/{$notifiable->token}");

    return (new MailMessage)
        ->subject('Confirm User')
        ->greeting("Dear {$notifiable->name},")
        ->line('Please click the button below to confirm that the concerned user is your staff')
        ->action('Confirm User', $confirmUrl)
        ->line('If you did not know the concerend staff, no further action is required.');
}

Table/Schema

public function up()
{
    Schema::create('confirm_user_tokens', function (Blueprint $table) {
        $table->bigIncrements('id');
        $table->unsignedInteger('user_id')->default(0);
        $table->unsignedInteger('concerned_user')->default(0);
        $table->string('token')->default(0);
        $table->string('status')->default('0');
        $table->timestamps();
    });
}
Karl Hill
  • 12,937
  • 5
  • 58
  • 95

1 Answers1

2

Try this. Create a collection where you can store all newly created ConfirmUserToken then find it inside your ConfirmUserNotification

Something like this..

RegisterController

$usersToken = collect(); // Create collection

foreach ($users as $u) {
    $cutoken = ConfirmUserToken::create([
        'user_id' => $u->id,
        'concerned_user' => $user->id,
        'token' => Hash::make(now()),
    ]);
    $cutoken->user()->associate($u);

    $usersToken->add($cutoken); // Store new ConfirmUserToken
}

 // pass the $usersToken object
\Notification::send($users, new ConfirmUser($usersToken));

ConfirmUserNotification

public $usersToken; 

public function __construct($usersToken)
{
   $this->usersToken = $usersToken;
}


public function toMail($notifiable)
{
    // Find the notifiable user to the object.
    $userToken = $this->usersToken->where('user_id', $notifiable->id)->first();
    // use the token from the first result above. 
    $confirmUrl = url("confirmUser/{$notifiable->id}/{$userToken->token}");

    return (new MailMessage)
        ->subject('Confirm User')
        ->greeting("Dear {$notifiable->name},")
        ->line('Please click the button below to confirm that the concerned user is your staff')
        ->action('Confirm User', $confirmUrl)
        ->line('If you did not know the concerend staff, no further action is required.');
}

Hope the idea can help. Good Luck.

Kenneth
  • 2,813
  • 3
  • 22
  • 46