You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Laravel 8使用laravel-ui-bootstrap时如何限制未验证邮箱用户登录

解决方案

第一步:配置User模型开启邮箱验证

这是Laravel启用邮箱验证的核心前提,打开app/Models/User.php修改类定义,实现MustVerifyEmail接口:

<?php

namespace App\Models;

use Illuminate\Contracts\Auth\MustVerifyEmail;
use Illuminate\Foundation\Auth\User as Authenticatable;
use Illuminate\Notifications\Notifiable;

class User extends Authenticatable implements MustVerifyEmail
{
    use Notifiable;

    // 原有模型其他代码保持不变
}

第二步:修正路由配置

你当前的路由文件存在重复定义根路径、引用不存在的PagesController、受限路由未绑定验证中间件的问题,直接替换routes/web.php内容为以下配置即可:

<?php

use Illuminate\Support\Facades\Route;
use Illuminate\Support\Facades\Auth;

// 公开路由,无需登录和邮箱验证
Route::get('/', function () {
    return view('main');
});

// 注册登录、注册、邮箱验证等系统自带路由,开启验证功能
Auth::routes(['verify' => true]);

// 需要登录+邮箱验证才能访问的路由组
Route::middleware(['auth', 'verified'])->group(function() {
    Route::get('/home', function() {
        return view('home');
    })->name('home');

    Route::get('/user/profile', function() {
        return view('profile');
    })->name('profile');
});

第三步:配置邮件发送参数

要确保验证邮件能正常发送,需要修改项目根目录下.env文件的邮件配置,参考示例如下(根据你实际使用的邮件服务调整参数):

MAIL_MAILER=smtp
MAIL_HOST=smtp.qq.com
MAIL_PORT=465
MAIL_USERNAME=你的发件邮箱地址
MAIL_PASSWORD=你的邮箱授权码
MAIL_ENCRYPTION=ssl
MAIL_FROM_ADDRESS=你的发件邮箱地址
MAIL_FROM_NAME="${APP_NAME}"

配置完成后执行php artisan config:cache清空配置缓存即可生效。

可选:登录环节直接拦截未验证用户

默认配置下未验证用户可以正常登录,访问受限路由时才会跳转验证提示页。如果需要在登录时就直接拦截,可在app/Http/Controllers/Auth/LoginController.php中添加以下方法:

protected function authenticated(Request $request, $user)
{
    if (!$user->hasVerifiedEmail()) {
        auth()->logout();
        return redirect()->route('verification.notice')->with('error', '请先验证邮箱后再登录');
    }
    return redirect()->intended($this->redirectPath());
}

内容的提问来源于stack exchange,提问作者Pleinair

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.28 03:36:04