我们是否可以在用户注册时动态启用/禁用电子邮件验证?
我认为,为了设置电子邮件验证,我们应该在 routes 上设置 Auth::routes(['verify' => true]);
并在用户模型,我们应该设置class User extends Authenticatable Implements MustVerifyEmail
但是,有什么简单的方法可以动态地执行此操作吗? 因此,假设我们在管理面板中设置启用/禁用。 根据它,我们可以在前面的认证页面设置启用/禁用吗?
最佳答案
您可以简单地操作 users
表中的 email_verified_at
列。
我建议使用观察者:
php artisan make:observer UserObserver --model=User
您可以通过配置或数据库来决定是否使用验证邮件。
用户观察者
class UserObserver
{
/**
* Handle the user "created" event.
*
* @param \App\User $user
* @return void
*/
public function created(User $user)
{
// Let's say you use config
if (config('app.email_verification') == false) {
$user->email_verified_at = now();
$user->save();
}
}
//
}
要确定电子邮件发送,您可以重写用户模型中的sendEmailVerificationNotification
:
/**
* Send the email verification notification.
*
* @return void
*/
public function sendEmailVerificationNotification()
{
if (config('app.email_verification')) {
$this->notify(new VerifyEmail);
}
}
并在用户类定义之前添加下一行:
use Illuminate\Auth\Notifications\VerifyEmail;
更新
要将 email_verified_at
保持为 null
,您可以删除观察者,然后更新您的 Auth::routes
,如下所示:
web.php
Auth::routes([
'verify' => config('app.email_verification')
]);
Route::group([
'middleware' => [config('app.email_verification') ? 'verified' : null]
], function () {
// protected routes
Route::get('dashboard', 'DashboardController@index');
});
关于php - Laravel 电子邮件验证一键禁用和启用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60712965/