I'm new to Laravel (only experienced Laravel 5, so no legacy hang up here)
I'd like to know how to extend the core Request class. In addition to how to extend it, i'd like to know if it's a wise design decision to do so.
I've read through the documentation extensively (especially with regards to registering service providers and the manner in which it provides Facades access to entries within the dependency container) - but I can see (and find) no way to replace the \Illuminate\Http\Request
instance with my own
I was able to add custom request object using
FormRequest
in Laravel 5.5 as follows.First, just create
FormRequest
:php artisan make:request MyRequest
Then just make it look like this:
You can then use
MyRequest
as drop-in replacement in any function that takesRequest
as parameter:I do realize that
FormRequest
s are actually meant to be used for a different purpose, but whatever works.Documentation on
FormRequest
: https://laravel.com/docs/5.0/validation#form-request-validationI guess you will have to extend also
RequestForm
. I use trait to avoid code duplication. Code below is relevant for Laravel 5.3.app/Http/ExtendRequestTrait.php
app/Http/Request.php
app/Http/FormRequest.php
For phpunit test working you will have to override
call
method to make it using rightRequest
class hereRequest::create
.test/TestCase.php
and don't forget to switch
Illuminate\Http\Request::capture()
toApp\Http\Request::capture()
inpublic/index.php
file and to add$app->alias('request', 'App\Http\Request');
after or inside$app = require_once __DIR__.'/../bootstrap/app.php';
I was working on the same issue today and I think it's worth mention that you may just change
to
without adding line
because inside
capture()
method laravel actually binds provided class to service container with 'request' as a keyHere is Official Document: Request Lifecycle
Content of app/Http/CustomRequest.php
add this line to public/index.php
after
change the code at public/index.php
to
Yerkes answer inspired me to write a custom class, for use with pagination, but only on specific requests
I then also had to register a new ServiceProvider in /config/app.php, which looks like
Now I can simply inject the PaginatedRequest in my controller methods only when I need it