Laravel Blade 仅在未登录时显示

Posted

技术标签:

【中文标题】Laravel Blade 仅在未登录时显示【英文标题】:Laravel Blade Display Only if Not Logged In 【发布时间】:2019-05-05 05:49:18 【问题描述】:

我正在使用 Laravel 的中间件,如果用户未通过身份验证,我会尝试使用空 div。否则,我试图拥有一个允许用户创建帐户的 div。我尝试了以下方法:

@auth
    <div class="form-group col-md-6"></div>
@else
    <div class="form-group col-md-6">
        <h6>Create Account</h6>
    </div>
@endauth

路线

Route::get('/checkout', 'CheckoutController@index')->name('checkout.index')->middleware('auth');
Route::get('/guestCheckout', 'CheckoutController@index')->name('guestCheckout.index');

CheckoutController.php

if (auth()->user() && request()->is('guestCheckout')) 
    return redirect()->route('checkout.index');

以上方法不起作用,我尝试过删除历史记录、清除缓存等,但无济于事。建议?谢谢!

【问题讨论】:

定义“不起作用”。会发生什么?你看到哪两个? 空 div,但用户未登录。我试图将其放在结帐/访客结帐页面上,我想我可能是因为我设置了 CheckoutController.php .我将在顶部添加更多信息。 【参考方案1】:

有现成的方法可以做到这一点!

@guest
  <div class="form-group col-md-6>
  </div>
@else
  <div class="form-group col-md-6>
    <h6>Create Account</h6>
  </div>
@endguest

如果我是你,你就不需要中间件了。

【讨论】:

我试过了,还是不行,所有情况下都会显示空的div。 Laravel 的哪个版本?【参考方案2】:

如果用户未通过身份验证,则尝试使用空 div...

您的刀片设置非常接近。试试这个!

@auth 
 <!-- the user is authenticated --> 
 <div class="form-group col-md-6>
 </div>

@endauth <!-- note the end auth --> 


@guest
 <!-- the user is NOT authenticated --> 
 <div class="form-group col-md-6>
    <h6>Create Account</h6>
 </div>
@endguest

你可以阅读更多关于这个here

至于您的控制器,请尝试使用:

if( Auth::check() ) 

    // The user is authenticated.. 

 else 
    // The user is NOT authenticated.. 

【讨论】:

@MatthewSpir​​e 你试一试了吗?【参考方案3】:

当前 (Laravel 8) 的方法是使用 Auth 辅助指令。 https://laravel.com/docs/8.x/blade#authentication-directives

@auth
This only shows for logged in users
@endauth

@guest
This only shows for guests
@endguest

【讨论】:

【参考方案4】:

你可以这样做

    <ul>        
      @guest
        @if (Route::has('login'))
          <li><a class="nav-link scrollto Request::url() === route('login') ? 'active' : ''" href="route('login')">Login</a></li>
        @endif
        @if (Route::has('register'))
          <li><a class="nav-link scrollto Request::url() === route('register') ? 'active' : ''" href="route('register')">Register</a></li>
        @endif
        @else
        <li class="dropdown"><a href="#"><span> Auth::user()->name </span> <i class="bi bi-chevron-down"></i></a>
            <ul>
              <li>
                <a href=" route('logout') " onclick="event.preventDefault(); document.getElementById('logout-form').submit();"> __('Logout') </a>
                <form id="logout-form" action=" route('logout') " method="POST" class="d-none">
                      @csrf
                </form>
              </li>
            </ul>
          </li>
      @endguest
    </ul>

【讨论】:

以上是关于Laravel Blade 仅在未登录时显示的主要内容,如果未能解决你的问题,请参考以下文章

仅在引导导航栏折叠时显示链接文本

css SEO Helper:仅在登录时显示标题的彩色标记:

仅在登录 MVC .net 站点时显示 <li> 项

不知何故,某些 css 仅在用户登录时显示 - 而对已注销的用户不显示。 HTML/CSS

用户连接时显示消息 laravel 6 *

Laravel Web 中间件组在用户未登录时显示页面