首页 > 解决方案 > Laravel 5.7 自定义重发邮件方法

问题描述

我自定义了我的 LoginController 以防止用户在未验证帐户时登录,因为这不是 Laravel 的默认行为。

既然用户正在登录并且帐户没有经过验证,我问他是否想要一个新的邮件通知来验证他的帐户。由于我没有$request->user()我不知道如何覆盖此方法:

验证控制器.php

public function resend(Request $request)
{
    if ($request->user()->hasVerifiedEmail()) {
        return redirect($this->redirectPath());
    }

    $request->user()->sendEmailVerificationNotification();

    return back()->with('resent', true);
}

我考虑过获取用户的邮件,但我怎样才能根据他的邮件而不是user()Laravel 期望的那样向他发送电子邮件?

标签: laravel

解决方案


您有几个选项,其中最简单的方法是使用签名 URL来允许resend接受用户id参数,然后当用户登录并且未通过验证时,您将他们重定向到resend页面id以识别他们的帐户没有活动的用户会话。

例如,您的登录控制器将如下所示:

if (! $user->hasVerifiedEmail()()) {
    return redirect()->to(URL::signedRoute('resend', ['id' => $user->id]));
}

你的VerificationController@resend方法看起来像这样:

public function resend(Request $request)
{
    if ($request->input('id') && $request->hasValidSignature()) {
        $user = User::findOrFail($request->input('id'));
    }

    $user = $user ?: $request->user();

    if ($user->hasVerifiedEmail()) {
        return redirect($this->redirectPath());
    }

    $user->sendEmailVerificationNotification();

    return back()->with('resent', true);
}

也就是说,Laravel 包含用于要求电子邮件验证的中间件:它确实允许登录,但在用户验证之前不允许用户做任何事情,因此除非您有理由完全阻止登录,否则中间件可以满足您的需求。您可以在此处找到有关中间件的信息。


推荐阅读