Search code examples
phplaravellaravel-5lumenlaravel-middleware

Adding values to request array in Laravel middleware is a good practice?


I have an authentication middle ware to check the validity of the passed api key. I fetch user id from the database store it to the request array so that the requesting page will get the userid.

  public function handle($request, Closure $next) {

        $key = $request->get('key');

        $user = User::where('token', '=' ,$key)->first();

                if($user != null){

                    $request->request->add(['middlewareUserID' => $user->id]);
                    return $next($request);
                  }
                  else {
                    return response(401);
                  }
    }

Is it a good practice?


Solution

  • I would say this is not necessary in such case.

    I would use code similar to this:

    use Illuminate\Contracts\Auth\Guard;
    
    class YourMiddleware 
    {
        protected $guard;
    
        public function __construct(Guard $guard)
        {
            $this->guard = $guard;
        }
    
        public function handle($request, Closure $next) {
    
            $key = $request->get('key');
    
            $user = User::where('token', '=' ,$key)->first();
    
            if(!$user){
               return response(401);
            }
    
            $this->guard->setUser($user);
            return $next($request);
    
        }
    }
    

    so when there is user for given token you can authenticate user in line $this->guard->setUser($user); and when the token is invalid you return return response(401);

    I don't see any need to set this user id to request as you showed.