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

Laravel Blade:如何检测任意Guard的@auth登录状态

解决Laravel模板中检测任意Guard登录状态的问题

嘿,这个场景我太熟悉了!Laravel的Blade模板默认的@auth指令确实只检测配置里的默认Guard(也就是你说的web),但要检测特定Guard或者任意Guard的登录状态,其实有几种简单的方法:

1. 检测单个特定Guard的登录状态

直接给@auth指令加上Guard名称作为参数就行,这样就能精准检测对应Guard下的用户是否已登录:

<!-- 检测管理员Guard登录状态 -->
@auth('admin')
    <div>
        欢迎管理员!
        <form action="{{ route('admin.logout') }}" method="POST">
            @csrf
            <button type="submit">管理员登出</button>
        </form>
    </div>
@endauth

<!-- 检测普通用户Guard登录状态 -->
@auth('web')
    <div>
        欢迎普通用户!
        <form action="{{ route('logout') }}" method="POST">
            @csrf
            <button type="submit">普通用户登出</button>
        </form>
    </div>
@endauth

2. 检测任意Guard是否有登录用户

如果你的需求是只要有任意一个Guard下的用户登录,就显示登出按钮,可以直接用逻辑判断组合多个Guard的检测结果:

@if(Auth::guard('admin')->check() || Auth::guard('web')->check())
    <div class="logout-section">
        <!-- 根据登录的Guard显示对应登出按钮 -->
        @if(Auth::guard('admin')->check())
            <form action="{{ route('admin.logout') }}" method="POST">
                @csrf
                <button type="submit">管理员登出</button>
            </form>
        @else
            <form action="{{ route('logout') }}" method="POST">
                @csrf
                <button type="submit">普通用户登出</button>
            </form>
        @endif
    </div>
@endif

如果后续可能增加更多Guard,不想每次都修改模板,还可以自定义一个Blade指令来简化操作:
在app/Providers/AppServiceProvider.php的boot方法里添加:

public function boot()
{
    // 自定义检测任意Guard登录的指令
    Blade::directive('anyauth', function () {
        // 这里可以添加所有需要检测的Guard
        return "<?php if(Auth::guard('admin')->check() || Auth::guard('web')->check()): ?>";
    });

    Blade::directive('endanyauth', function () {
        return "<?php endif; ?>";
    });
}

之后在模板里就能像用@auth一样使用自定义指令:

@anyauth
    <!-- 任意用户登录后显示的内容 -->
@endanyauth

小提示

  • 除了@auth('guard-name'),你也可以在模板里直接用Auth::guard('guard-name')->check()来做更灵活的逻辑判断
  • 如果需要获取当前登录的Guard用户,用Auth::guard('guard-name')->user()就行

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.25 03:32:02