如何根据登录用户和来宾用户对 Laravel 路由进行分组

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/37517344/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-14 13:54:13  来源:igfitidea点击:

How to group laravel routes based on logged users and guest users

phplaravelsentinel

提问by Chathurika Mahanama

I want to group the Laravel 5 routs based on the logged users and guest users. Is there any inbuilt framework methods in Laravel 5 to do this?

我想根据登录用户和来宾用户对 Laravel 5 路由进行分组。Laravel 5 中是否有任何内置的框架方法可以做到这一点?

回答by Giedrius Kir?ys

Yes, there are some: https://laravel.com/docs/master/middleware#assigning-middleware-to-routesauthfor authorized and guestfor guests.

是的,有一些:https: //laravel.com/docs/master/middleware#assigning-middleware-to-routesauth用于授权和guest访客。

Route::group(['middleware' => ['auth']], function () {
    //only authorized users can access these routes
});

Route::group(['middleware' => ['guest']], function () {
    //only guests can access these routes
});

回答by Manula Thantriwatte

Yes, you can do this by updating following method in Authenticate.php

是的,您可以通过更新 Authenticate.php 中的以下方法来做到这一点

public function handle($request, Closure $next, $guard = null)
    {
        if (Auth::guard($guard)->guest()) {

            if ($request->ajax() || $request->wantsJson()) {
                return response('Unauthorized.', 401);
            } else {
                return redirect()->guest('login');
            }
        }

        return $next($request);
    }

If you are using Sentinel you can check the the logged user from

如果您使用的是 Sentinel,则可以从以下位置检查登录的用户

Sentinel::check()instead of Auth::guard($guard)->guest()

Sentinel::check()代替 Auth::guard($guard)->guest()

Then you can group the routs as follows.

然后您可以按如下方式对路由进行分组。

Route::group(['middleware' => ['auth']], function () {
    // Authorized routs
});

Route::group(['middleware' => ['guest']], function () {
    // Guest routs
});