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

如何在Fortify中实现用户登录成功时的Flash消息提示

在Fortify中实现登录成功的Flash消息

有两种常用方式可以实现这个需求,以下是具体步骤:

方法一:监听登录事件

通过Laravel的事件系统捕获登录成功事件,添加Flash消息:

  1. 生成登录成功监听器
    执行Artisan命令创建监听器:
    php artisan make:listener LoginSuccessListener
    
  2. 修改监听器逻辑
    打开app/Listeners/LoginSuccessListener.php,在handle方法中添加Flash消息:
    <?php
    
    namespace App\Listeners;
    
    use Illuminate\Auth\Events\Login;
    use Illuminate\Support\Facades\Session;
    
    class LoginSuccessListener
    {
        public function handle(Login $event)
        {
            Session::flash('success-login', '登录成功!欢迎回来');
        }
    }
    
  3. 注册监听器
    打开app/Providers/EventServiceProvider.php,在$listen数组中添加关联:
    protected $listen = [
        // 其他事件...
        \Illuminate\Auth\Events\Login::class => [
            \App\Listeners\LoginSuccessListener::class,
        ],
    ];
    

方法二:自定义Fortify的登录响应

直接利用Fortify提供的钩子修改登录成功后的逻辑:

  1. (可选)发布Fortify配置
    若未发布过Fortify配置文件,执行以下命令:
    php artisan vendor:publish --provider="Laravel\Fortify\FortifyServiceProvider"
    
  2. 修改Fortify服务提供者
    打开app/Providers/FortifyServiceProvider.php,在boot方法中添加authenticated钩子:
    <?php
    
    namespace App\Providers;
    
    use Illuminate\Support\Facades\Session;
    use Laravel\Fortify\Fortify;
    use Illuminate\Support\ServiceProvider;
    
    class FortifyServiceProvider extends ServiceProvider
    {
        public function boot()
        {
            // 其他Fortify配置...
    
            Fortify::authenticated(function ($request, $user) {
                Session::flash('success-login', '登录成功!欢迎回来');
            });
        }
    }
    

视图使用说明

你提供的Blade视图代码可直接使用,无需修改:

@if(session()->has('success-login'))
    <div class="alert alert-info alert-dismissible fade show" role="alert">
        <strong>{{ session()->get('success-login') }}</strong>
        <button type="button" class="close" data-dismiss="alert" aria-label="Close">
            <span aria-hidden="true">&times;</span>
        </button>
    </div>
@endif

内容的提问来源于stack exchange,提问作者Yarham Fitrohiman Pahlawi

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.26 04:15:29