Laravel 5.7电子邮件验证到期时间

esk*_*imo 6 laravel laravel-5.7

我想自定义用户验证内置Auth(自5.7版本开始)以来发生的电子邮件地址的时间。

config/auth有:

'passwords' => [
        'users' => [
            'provider' => 'users',
            'table' => 'password_resets',
            'expire' => 60,
        ],
    ],
Run Code Online (Sandbox Code Playgroud)

但是我还没有发现类似的电子邮件验证方法。官方文档中也没有提及。

Olu*_*kin 6

实际上,Laravel中没有该选项,但是由于laravel使用以下内容:

  • 特征MustVerifyEmail(在Illuminate\Foundation\Auth\UserUser模型扩展的类中)

  • 活动和通知

MustVerifyEmail特征中,有一种称为的方法sendEmailVerificationNotification。这是使用@nakov答案VerifyEmail引用的Notification 类及其功能的地方:verificationUrl

/**
 * Send the email verification notification.
 *
 * @return void
 */
public function sendEmailVerificationNotification()
{
    $this->notify(new Notifications\VerifyEmail);
}
Run Code Online (Sandbox Code Playgroud)

既然我们知道这一点,我们可以执行以下操作:

  • 将扩展Notifications\VerifyEmail到我们的自定义VerifyEmail
  • 覆盖执行 verificationUrl
  • 重写模型中sendEmailVerificationNotification方法的实现User以使用我们的新VerifyEmail类。

完成上述操作后,我们的User模型将具有以下方法:

/**
 * Send the email verification notification.
 *
 * @return void
 */
public function sendEmailVerificationNotification()
{
    $this->notify(new \App\Services\Verification\VerifyEmail);
}
Run Code Online (Sandbox Code Playgroud)

现在,我们使用我们的自定义VerifyEmail类。然后我们的新VerifyEmail类将如下所示:

namespace App\Services\Verification;

use Illuminate\Support\Carbon;
use \Illuminate\Support\Facades\URL;

class VerifyEmail extends \Illuminate\Auth\Notifications\VerifyEmail
{
    protected function verificationUrl($notifiable)
    {
        return URL::temporarySignedRoute(
            'verification.verify', Carbon::now()->addMinute(3), ['id' => $notifiable->getKey()]
        );  //we use 3 minutes expiry
    }
}
Run Code Online (Sandbox Code Playgroud)

好吧,除了说明之外,该过程非常简单。我希望很容易掌握。干杯!


Jam*_*mes 6

虽然这个问题专门针对Laravel 5.7,但我觉得值得一提的是,从Laravel 5.8开始,可以通过config变量实现这一点。我自定义验证到期时间的搜索将这个问题作为最高结果返回,因此添加了我。

如果我们检出Illuminate\Auth\Notifications\VerifyEmail,该verificationUrl方法现在如下所示:

protected function verificationUrl($notifiable)
{
    return URL::temporarySignedRoute(
        'verification.verify',
        Carbon::now()->addMinutes(Config::get('auth.verification.expire', 60)),
        ['id' => $notifiable->getKey()]
    );
}
Run Code Online (Sandbox Code Playgroud)

这样,我们只需添加此块即可config/auth.php自定义时间,而无需扩展类或其他任何东西:

'verification' => [
    'expire' => 525600, // One year - enter as many mintues as you would like here
],
Run Code Online (Sandbox Code Playgroud)

更新:我已经在我的博客上介绍了上述方法,以及有关通过覆盖该verificationUrl方法以提供更多灵活性的自定义流程的另一种方法。