如何在登录和注销时两次使用 / (index) 路由?

How do I use the / (index) route twice for both logged in and logged out?

我正在做一个 Laravel 项目。该项目有一个 public(站点的非认证部分)和一个认证部分(管理员)。

我正在尝试使用 / 路由来显示 public 主页视图,然后在通过身份验证时,我希望使用相同的 / 路由来显示经过管理员身份验证的视图。

这是尝试的代码:

routes.php

Route::auth();

Route::get('/', function () {
        return view('Public.home');
    });

Route::group(['middleware' => ['auth']], function () { 

    Route::get('/', function () {
        return view('Authenticated.home');
    });
});

问题 当我注销并尝试访问 / 路由时,Public 控制器(Public.home)被认为是经过身份验证的路由(位于上面路由组中的 'auth' 中间件下) .

中间件 auth 设置为在访问任何受保护(已验证)路由时重定向到 /。

Authenticate.php

<?php

namespace App\Http\Middleware;

use Closure;
use Illuminate\Support\Facades\Auth;

class Authenticate
{
    /**
     * Handle an incoming request.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \Closure  $next
     * @param  string|null  $guard
     * @return mixed
     */
    public function handle($request, Closure $next, $guard = null)
    {
        if (Auth::guard($guard)->guest()) {
            if ($request->ajax() || $request->wantsJson()) {
                return response('Unauthorized.', 401);
            }

            return redirect()->guest('/');
        }

        return $next($request);
    }
}

我正在使用 Laravel 5.2。

有几种方法可以解决这个问题。

第一个是从 auth 中间件中排除您的 ('/') 路由,然后编写您自己的路由来检查它们是否已登录,并根据 return 适当的视图那。

像这样的东西就可以了:

public function handle($request, Closure $next)
{
    if (Auth::check())
    {
        //The user is logged in
        return view('Authenticated.home');
    }

    else
    {
        //The user is not logged in
        return view('Public.home');
    }
}

有关编写自己的中间件的更多信息,请参阅相关文档。

或者,您可以只创建一个视图 ('home'),然后使用 if 语句检查他们是否已登录。

像这样的东西就可以了:

@if (Auth::check())
    //User is logged in
    //HTML that we want to show to authenticated user
@else
    //User is not logged in
    //HTML that we want to show to general public
@endif