
There are multiple ways to extend or modify theRequest
object in Laravel. I'd like to show you a method, which in my opinion is the cleanest one.
Macro
You may already know about themacro
method. It's the most obvious way to introduce new methods to theRequest
object but it has some downsides.
Request::macro('project',function(){return$this->user();});
This solution is simple but it has some flaws:
• You cannot override or change existing methods.
• It's not obvious where these new methods are coming from.
• No IDE autocompletion.
Custom Request Object
I like creating my ownRequest
object.
<?phpnamespaceApp\Http;useIlluminate\Http\RequestasLaravelRequest;classRequestextendsLaravelRequest{/** * Get the team making the request. * * @param string|null $guard * @return mixed */publicfunctionteam($guard=null){return$this->user($guard);}}
It's simple, clean and straightforward. Much better than introducing new methods via "macros".
Now, we need to instruct Laravel to use this new custom class as a base.
Simply override thehandle
method in ourApp\Http\Kernel
class to use your customRequest
object.
<?phpnamespaceApp\Http;useApp\Http\Request;useIlluminate\Foundation\Http\KernelasHttpKernel;classKernelextendsHttpKernel{// .../** * Handle an incoming HTTP request. * * @param \Illuminate\Http\Request $request * @return \Illuminate\Http\Response */publicfunctionhandle($request){returnparent::handle(Request::createFrom($request));}}
... and finally, alias your newApp\Http\Request
class so the container always returns the same instance.
$this->app->alias('request',Request::class);
Happy Coding!
Top comments(2)

This is absolutely fantastic. Been looking for a way to do this, and the macro method wasn't just a clean way. Thanks a tad much@titasgailius
For further actions, you may consider blocking this person and/orreporting abuse