php – 我如何使用/(索引)路由两次登录和注销?

发布时间:2022-04-30 发布网站:脚本宝典
脚本宝典收集整理的这篇文章主要介绍了php – 我如何使用/(索引)路由两次登录和注销?脚本宝典觉得挺不错的,现在分享给大家,也给大家做个参考。
我正在研究一个Laravel项目.该项目有一个公共的(未经过身份验证的网站部分)和一个经过身份验证的部分(管理员).

我正在尝试使用/ route显示公共主页视图,然后在进行身份验证时,我希望显示管理身份验证视图的相同/路由.

这是尝试的代码

routes.PHP文件

Route::auth();

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

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

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

问题
当我注销并尝试访问/ route时,公共控制器(Public.home)被视为经过身份验证的路由(位于上面路由组中的“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中间件中排除你的(‘/’)路由并编写自己的路由以检查它们是否登录并根据它返回相应的视图.

像这样的东西可以做到一点

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

脚本宝典总结

以上是脚本宝典为你收集整理的php – 我如何使用/(索引)路由两次登录和注销?全部内容,希望文章能够帮你解决php – 我如何使用/(索引)路由两次登录和注销?所遇到的问题。

如果觉得脚本宝典网站内容还不错,欢迎将脚本宝典推荐好友。

本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
如您有任何意见或建议可联系处理。小编QQ:384754419,请注明来意。