Easy way to extend the Request class? #38650
-
Is there an easy way to extend the default For example, the Currently to achieve that this is what I did in my
Feels a little hacky and additionally getting |
Beta Was this translation helpful? Give feedback.
Replies: 2 comments 3 replies
-
Hi! You can create your own descendant of Laravel Request. For example:
And then use it directly in your index.php:
And that all! However in your artisan you would still get Laravel native request. |
Beta Was this translation helpful? Give feedback.
-
The default request class is macroable. framework/src/Illuminate/Http/Request.php Lines 20 to 25 in eb378fc So you could simply extend the request class. Put this in the boot method of one of your service providers: Request::macro('apiVersion', function () {
return request()->header('api-version') ?? 'latest';
}); And then in your controller or wherever you need the api version: $apiVersion = request()->apiVersion(); |
Beta Was this translation helpful? Give feedback.
The default request class is macroable.
framework/src/Illuminate/Http/Request.php
Lines 20 to 25 in eb378fc
So you could simply extend the request class. Put this in the boot method of one of your service providers:
And then in your controller or wherever you need the api version: