gpt4 book ai didi

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

转载 作者:可可西里 更新时间:2023-10-31 23:17:06 25 4
gpt4 key购买 nike

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

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

这是尝试的代码:

routes.php

Route::auth();

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

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

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

问题当我注销并尝试访问/路由时,公共(public) Controller (Public.home) 被视为经过身份验证的路由(位于上面路由组中的“auth”中间件下)。

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

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 中间件中排除你的 ('/') 路由并编写你自己的来检查他们是否登录并返回基于此的适当 View 。

像这样的东西就可以了:

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');
}
}

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

或者,您可以只创建一个 View ('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

关于php - 如何在登录和注销时两次使用/(index) 路由?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38547743/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com