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();
});
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);
}
}
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)
);
}
}
... and finally, alias your new App\Http\Request
class so the container always returns the same instance.
$this->app->alias('request', Request::class);
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
Awesome. That request alias save me.