Movatterモバイル変換


[0]ホーム

URL:


Skip to content
DEV Community
Log in Create account

DEV Community

Cover image for Roll your own Request object in Laravel
Titas Gailius
Titas Gailius

Posted on

     

Roll your own Request object in Laravel

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();});
Enter fullscreen modeExit fullscreen mode

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);}}
Enter fullscreen modeExit fullscreen mode

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));}}
Enter fullscreen modeExit fullscreen mode

... and finally, alias your newApp\Http\Request class so the container always returns the same instance.

$this->app->alias('request',Request::class);
Enter fullscreen modeExit fullscreen mode

Happy Coding!

Top comments(2)

Subscribe
pic
Create template

Templates let you quickly answer FAQs or store snippets for re-use.

Dismiss
CollapseExpand
 
robertkeli profile image
Robert Ndung'u
  • Joined

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

CollapseExpand
 
azharlihan profile image
Azhar Lihan
  • Joined

Awesome. That request alias save me.

Are you sure you want to hide this comment? It will become hidden in your post, but will still be visible via the comment'spermalink.

For further actions, you may consider blocking this person and/orreporting abuse

  • Joined

More fromTitas Gailius

DEV Community

We're a place where coders share, stay up-to-date and grow their careers.

Log in Create account

[8]ページ先頭

©2009-2025 Movatter.jp