obada123's avatar

Extending Laravel Illuminate\Http\Request

Hello everyone,

I'm trying to extend Laravel's Illuminate\Http\Request class to create a custom request class and use it in a middleware, but I'm having some trouble getting it to work. Here's what I've done so far:

Created a new class called CustomRequest that extends Illuminate\Http\Request. In this class, I've added a new method called apiKey that retrieves the value of the API-KEY header from the request and performs some validation on it.

use Illuminate\Http\Request;

 class CustomRequest extends Request {
     public function apiKey()
     {
         $apiKey = $this->header('API-KEY');

         /* Some validation on the  API KEY */

         return $apiKey;
     }
}

Created a new service provider called RequestServiceProvider that binds Illuminate\Http\Request to CustomRequest and registered it Config\app.php. This tells Laravel's service container to use CustomRequest whenever an instance of Illuminate\Http\Request is requested.


class RequestServiceProvider extends ServiceProvider {
	public function register() {
        $this->app->bind('Illuminate\Http\Request', CustomRequest::class);
    }
}

Created a new middleware called TestMiddleware and registered it in Kernel.php.


class TestMiddleware {
  public function handle(Request $request, Closure $next) {
        dd(get_class($request));
    }
}

However, when I try to test my middleware, I'm getting an instance of Illuminate\Http\Request instead of CustomRequest. I'm not sure what is causing this issue.

Can anyone help me figure out what I'm doing wrong? I would really appreciate any advice or guidance.

0 likes
5 replies
Niush's avatar

Why not simply create an App\Services\ApiKeyValidator class with a setValidatedApiKey() function. Call this function from your service provider and inside the function do something like this:

public function setValidatedApiKey(Request $request) {
    // ...
    $request->attributes->add(['api_key' => 'your_validated_api_key']);
}

Then you can access it anywhere (e.g. middleware) using:

$request->attributes->get('api_key');
obada123's avatar

@Niush Because my intention in extending Illuminate\Http\Request is not limited to the apiKey functionality, but it is a crucial part of the overall functionality that I am trying to achieve.

Niush's avatar
Niush
Best Answer
Level 51

@obada123 If you must, then you can update the public/index.php file like such:

$response = $kernel->handle(
    $request = CustomRequest::capture()
)->send();

All the Request class resolved from container will be this CustomRequest instance.

1 like
obada123's avatar

@Niush Thank you, It worked !

In this case, there is no need for this line

        $this->app->bind('Illuminate\Http\Request', CustomRequest::class);

in my RequestServiceProvider, right ?

Please or to participate in this conversation.