首页 > 解决方案 > 在 laravel 中设置自定义用户验证链接问题

问题描述

我一直在尝试在 laravel 中向我的用户发送一封自定义验证电子邮件。

首先我运行这个

php artisan make:notification SendRegisterEmailNotifcation

SendRegisterEmailNotifcation.php在我的App/Notifications.

然后在我的用户控制器的存储方法中,我在用户插入完成后调用了该方法。

以下是我的商店功能,

public function store(Request $request)
    {
        request()->validate([
            'name' => ['required', 'alpha','min:2', 'max:255'],
            'last_name' => ['required', 'alpha','min:2', 'max:255'],
            'email' => ['required','email', 'max:255', 'unique:users'],
            'password' => ['required', 'string', 'min:12', 'confirmed','regex:/^(?=.*[a-z])(?=.*[A-Z])(?=.*\d)(?=.*[@$!%*?&])[A-Za-z\d@$!%*?&]{12,}$/'],
            'mobile'=>['required', 'regex:/^\+[0-9]?()[0-9](\s|\S)(\d[0-9]{8})$/','numeric','min:9'],
            'username'=>['required', 'string', 'min:4', 'max:10', 'unique:users'],   
            'roles'=>['required'],
            'user_roles'=>['required'],
        ]);

        //Customer::create($request->all());

        $input = $request->all();
        $input['password'] = Hash::make($input['password']);

        $user = User::create($input);
        $user->assignRole($request->input('roles'));

        //event(new Registered($user));
        $user->notify(new SendRegisterMailNotification());

        return redirect()->route('customers.index')
                        ->with('success','Customer created successfully. Verification email has been sent to user email.  ');
    }

这是我的SendRegisterMailNotification.php

<?php

namespace App\Notifications;

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

class SendRegisterMailNotification extends Notification
{
    use Queueable;

    /**
     * Create a new notification instance.
     *
     * @return void
     */
    public function __construct()
    {
        //
    }

    /**
     * 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('The introduction to the notification.')
                    ->action('Click Here to Activate', url('/'))
                    ->line('Thank you for using our application!');
    }

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

现在这个过程运行良好,新创建的用户正在接收他们的电子邮件。

但问题是

通常在 laravel 中激活链接具有一定的格式,一旦用户点击按钮,用户帐户就会被激活并将验证的日期时间存储在用户表中,链接也会在 60 分钟内过期。

样品验证链接,

http://test.site/email/verify/22/3b7c357f630a62cb2bac0e18a47610c245962182?expires=1588247915&signature=7e6869deb1b6b700dcd2a49b2ec66ae32fb0b6dc99aa0405095e9844962bb53c

但就我而言,我正在努力正确设置激活链接和流程,我该如何使用上述自定义电子邮件来做到这一点?

标签: phplaravellaravel-5laravel-6email-verification

解决方案


You can get the link to verify email by using verificationUrl() function of VerifyEmail class from Illuminate\Auth\Notifications\VerifyEmail library in your SendRegisterMailNotification notification class.

Here it goes,

namespace App\Notifications;

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

class SendRegisterMailNotification extends VerifyEmail implements ShouldQueue
{
    use Queueable;

/**
     * Get the mail representation of the notification.
     *
     * @param  mixed  $notifiable
     * @return \Illuminate\Notifications\Messages\MailMessage
     */
    public function toMail($notifiable)
    {
        $actionUrl  = $this->verificationUrl($notifiable);  //call the verificationUrl() from base class
        $actionText  = 'Click here to verify your email';
        
        /*here, i am using view blades instead of markdown for email template*/
        return (new MailMessage)->subject('Verify your account')->view(
            'emails.user-verify',
            [
                'actionText' => $actionText,
                'actionUrl' => $actionUrl,
            ]);
    }

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

The emails.user-verify view looks like this

        <p>
            Please click the button below to verify your email address.
        </p>

        
        <a href="{{ $actionUrl }}" class="button">{{$actionText}}</a>
        
        <p>If you did not create an account, no further action is required.</p>

        <p>
            Best regards, <br><br>
            <strong>{{config('app.signature')}}</strong><br/>
            {{ config('app.signature-title')}}
        </p>

Or if you prefer markdown, you can use

public function toMail($notifiable)
{
    $url= $this->verificationUrl($notifiable);


      return (new MailMessage)
                    ->line('The introduction to the notification.')
                    ->action('Click Here to Activate', $url)
                    ->line('Thank you for using our application!');

}

推荐阅读