Laravel Auth in error pages

2019-06-24 04:55发布

When a user is logged into my application, there is a dropdown in the navigation to access administration. However, when a user stumbles across an error page (404, for instance) it doesn't show them being logged in. Instead it shows "Login". Why is this?

Here's my code.

@if (Auth::check())

    <ul class="nav navbar-nav navbar-right">
        <li class="dropdown">
            <a style="cursor: pointer;" class="dropdown-toggle" data-toggle="dropdown"><i class="glyphicon glyphicon-user"></i> {{ Auth::user()->name }} <b class="caret"></b></a>
            <ul class="dropdown-menu">
                <li>
                    <a href="/admin/dashboard"><i class="glyphicon glyphicon-tasks"></i> Dashboard</a>
                </li>
                <li role="separator" class="divider"></li>
                <li><a href="/logout"><i class="glyphicon glyphicon-log-out"></i> Logout</a></li>
            </ul>
        </li>
    </ul>

@else

    <ul class="nav navbar-nav navbar-right">
        <li><a href="/login"><i class="glyphicon glyphicon-log-in"></i> Login</a</li>
    </ul>

@endif

1条回答
爷、活的狠高调
2楼-- · 2019-06-24 05:33

It looks like Laravel only starts the session where it sees appropriate (which isn't a 404 page) as Daniel pointed out: https://github.com/laravel/framework/issues/11653.

To combat this (as the navigation bar is site-wide, including 404 pages) I added the StartSession class to the global middlwares.

protected $middleware = [
    \Illuminate\Foundation\Http\Middleware\CheckForMaintenanceMode::class
];

Now becomes...

protected $middleware = [
    \Illuminate\Foundation\Http\Middleware\CheckForMaintenanceMode::class,
    \Illuminate\Session\Middleware\StartSession::class
];
查看更多
登录 后发表回答