request-method-vs-input

There are many ways to get the request parameters in Laravel, such as request(), $request->input(), $request->get(), but there are a little different between request() and $request->input() when the parameter is not actually passed.

Sometimes it maybe cause some unexpected behavior, Let’s see:

1
2
3
4
5
6
7
Route::get('/test', function (Request $request) {
    dd(
        request('key', 'default'),
        $request->input('key', 'default'),
        $request->get('key', 'default'),
    );
});

When our request like this: http://localhost/test?key=, yes, we do not actually set a value for the key, the output will be:

1
2
3
"default" // the requst() return the default value
null // the $request->input() return null, not the default value
"default" // the $request->get() also return the default value

Interesting, right?