Is there any benefit to injecting the Request object into your controller method like this:
use Request;
class WidgetController
{
public function create(Request $request)
{
$name = $request->input('name');
}
}
Versus eliminating the use statement and object injection and simply using the helper:
class WidgetController
{
public function create()
{
$name = request('name');
}
}
The request
helper is just a shortcut to Request::input('name')
. The code for the request helper is defined like this request helper
app('request')->input($key, $default);
The app is the Container that manages the Dependency injection of Laravel. It will resolve the dependency that correspond to the name request
which is an instance of Illuminate\Http\Request
and call on it the method input
passing the name of the key you want to retrieve.
There is really no difference, one is a shortcut of the other.
The primary reason to use injection is because of testing. If you use request() then you need to initialize the Laravel app since request() calls app('request'). If app('request') is not initialized then your tests will generate an error.
When you use injection you pass on the Request object to the method. This means that during testing you can create your own "dummy" request and pass that on to the method without having to initialize app(). Then you can test the method and only the method without and dependencies to anything else.
First of all, code-styling and readability. The first one is way more readable. Second thing from top of my mind is that, if you use request()
helper, you can not validate the request.
Let's say your request must contain a parameter title
and body
. If the parameter is not there, it should never reach that endpoint. Using the helper()
, there is not way to do it. While, using the first method, there is really convenient way of doing that.
class StoreRequest extends FormRequest
{
public function rules()
{
return [
'title' => 'required',
'body' => 'sometimes'
];
}
}
And than just:
use StoreRequest;
class WidgetController
{
public function create(StoreRequest $request)
{
$name = $request->input('name');
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With