Search code examples
phpauthenticationmiddlewarelaravel-5.1laravel-middleware

How can I use laravel 5.1 middleware parameter for multiple auth and protected routes?


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.


Solution

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