dongxiangqian1855 2015-09-20 12:13
浏览 56
已采纳

如何为多个身份验证和受保护的路由使用laravel 5.1中间件参数?

I'm new to laravel 5.1. How can I use middleware parameter to protect my admin routes from users ? something like this:

Route::group(['middleware' => 'auth:admin'], function()    
/* Admin only Routes*/
{
   //////
});

I have a field "role" in my "users" table that get two values:

  • 1 for admin
  • 2 for users

In my application, users, have their protected route. I don't want to use packages.

  • 写回答

1条回答 默认 最新

  • doudi2229 2015-09-20 17:44
    关注

    You can do something like this. Inject the Guard class, then use it to check the user. You dont need to pass the parameter really. Just name your middleware 'admin' or something. The following middleware will check if the current user's role is admin, and if not, redirect to another route. You can do whatever you prefer on failure.

    <?php
    
    namespace Portal\Http\Middleware;
    
    use Closure;
    use Illuminate\Contracts\Auth\Guard;
    
    class Admin
    {
        /**
         * The Guard implementation.
         *
         * @var Guard
         */
        protected $auth;
    
        /**
         * Create a new filter instance.
         *
         * @param  Guard  $auth
         */
        public function __construct(Guard $auth)
        {
            $this->auth = $auth;
        }
    
        /**
         * Handle an incoming request.
         *
         * @param  \Illuminate\Http\Request  $request
         * @param  \Closure  $next
         * @return mixed
         */
        public function handle($request, Closure $next)
        {
            if($this->auth->user()->role != 'admin') {
                return redirect()->route('not-an-admin');
            }
            return $next($request);        
        }
    }
    

    In case you do want to pass the parameter, you can do this:

        public function handle($request, Closure $next, $role)
        {
            if($this->auth->user()->role != $role) {
                return redirect()->route('roles-dont-match');
            }
            return $next($request);        
        }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 微信会员卡等级和折扣规则
  • ¥15 微信公众平台自制会员卡可以通过收款码收款码收款进行自动积分吗
  • ¥15 随身WiFi网络灯亮但是没有网络,如何解决?
  • ¥15 gdf格式的脑电数据如何处理matlab
  • ¥20 重新写的代码替换了之后运行hbuliderx就这样了
  • ¥100 监控抖音用户作品更新可以微信公众号提醒
  • ¥15 UE5 如何可以不渲染HDRIBackdrop背景
  • ¥70 2048小游戏毕设项目
  • ¥20 mysql架构,按照姓名分表
  • ¥15 MATLAB实现区间[a,b]上的Gauss-Legendre积分