Laravel 9+Jetstream:注册后先验邮箱再跳转自定义页面
解决注册后先跳转邮箱验证页、验证完成后再到news页的方案
1. 调整news路由的中间件
确保未验证邮箱的用户无法直接访问news页面,访问时会被自动重定向到邮箱验证提示页。修改web.php中的路由:
Route::get('news', [CustomViewController::class, 'showNews']) ->middleware(['auth', 'verified']) // 添加verified中间件 ->name('news');
2. 自定义注册后的跳转逻辑
Jetstream/Fortify默认注册完成后会跳转到HOME常量指向的页面,我们需要修改这个逻辑,让未验证邮箱的新用户注册后直接进入邮箱验证提示页。
步骤2.1 创建自定义注册用户Action
在app/Actions/Fortify目录下创建RegisteredUserAction.php文件(目录不存在则自行创建),代码如下:
<?php namespace App\Actions\Fortify; use Laravel\Fortify\Contracts\RegisteredUserResponse; use Laravel\Fortify\Contracts\RegisterResponse; use Laravel\Fortify\Actions\RegisteredUserAction as FortifyRegisteredUserAction; class RegisteredUserAction extends FortifyRegisteredUserAction { /** * 处理注册用户后的响应跳转 * * @param mixed $user * @return \Laravel\Fortify\Contracts\RegisteredUserResponse */ public function handle($user): RegisteredUserResponse { // 若用户邮箱未验证,跳转到邮箱验证提示页 if (! $user->hasVerifiedEmail()) { return app(RegisterResponse::class)->to('/email/verify'); } // 已验证邮箱的用户跳转到news页面 return app(RegisterResponse::class)->to(config('fortify.home')); } }
步骤2.2 替换默认的注册Action
在app/Providers/FortifyServiceProvider.php的boot方法中,注册自定义Action替换Fortify默认的注册逻辑:
use App\Actions\Fortify\RegisteredUserAction; use Laravel\Fortify\Fortify; public function boot() { // 保留原有代码,添加以下内容 Fortify::registerUserUsing(RegisteredUserAction::class); }
3. 修改邮箱验证成功后的跳转目标
默认邮箱验证成功后会跳转到HOME页面,我们需要将目标改为news页,可通过以下两种方式实现:
方式一:修改默认验证控制器的跳转地址
如果项目中存在app/Http/Controllers/Auth/VerificationController.php,添加redirectTo属性:
protected $redirectTo = '/news';
方式二:自定义验证后的响应逻辑
在FortifyServiceProvider.php的boot方法中添加:
use Laravel\Fortify\Contracts\VerifyEmailResponse; $this->app->instance(VerifyEmailResponse::class, new class implements VerifyEmailResponse { public function to($request) { return redirect()->route('news'); } });
4. 验证效果
新用户注册后会直接跳转到邮箱验证提示页,完成验证后自动跳转至news页面;已验证邮箱的用户登录后,也会正常跳转到news页面。
内容的提问来源于stack exchange,提问作者Jefferson Farid
相关产品推荐
相关产品推荐

