DEV Community

loading...
Cover image for Roll your own Request object in Laravel

Roll your own Request object in Laravel

titasgailius profile image Titas Gailius ・1 min read

There are multiple ways to extend or modify the Request 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 the macro method. It's the most obvious way to introduce new methods to the Request object but it has some downsides.

Request::macro('project', function () {
    return $this->user();
});
Enter fullscreen mode Exit 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 own Request object.

<?php

namespace App\Http;

use Illuminate\Http\Request as LaravelRequest;

class Request extends LaravelRequest
{
    /**
     * Get the team making the request.
     *
     * @param  string|null  $guard
     * @return mixed
     */
    public function team($guard = null)
    {
        return $this->user($guard);
    }
}
Enter fullscreen mode Exit 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 the handle method in our App\Http\Kernel class to use your custom Request object.

<?php

namespace App\Http;

use App\Http\Request;
use Illuminate\Foundation\Http\Kernel as HttpKernel;

class Kernel extends HttpKernel
{
    // ...

    /**
     * Handle an incoming HTTP request.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return \Illuminate\Http\Response
     */
    public function handle($request)
    {
        return parent::handle(
            Request::createFrom($request)
        );
    }
}
Enter fullscreen mode Exit fullscreen mode

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

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

Happy Coding!

Discussion (0)

pic
Editor guide