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 如何让企业微信机器人实现消息汇总整合
  • ¥50 关于#ui#的问题:做yolov8的ui界面出现的问题
  • ¥15 如何用Python爬取各高校教师公开的教育和工作经历
  • ¥15 TLE9879QXA40 电机驱动
  • ¥20 对于工程问题的非线性数学模型进行线性化
  • ¥15 Mirare PLUS 进行密钥认证?(详解)
  • ¥15 物体双站RCS和其组成阵列后的双站RCS关系验证
  • ¥20 想用ollama做一个自己的AI数据库
  • ¥15 关于qualoth编辑及缝合服装领子的问题解决方案探寻
  • ¥15 请问怎么才能复现这样的图呀