Request::has() returns false even when parameter i

2019-02-04 12:53发布

问题:

URL: http://localhost/?v=

Code:

Route::get('/', ['as' => 'home', function()
{
    dd(Request::has('v'));
}]);

Output: false

What is going on? Is this a bug or am I doing something wrong?

回答1:

Request::has() will check if the item is actually set. An empty string doesn't count here.

What you are looking for instead is: Request::exists()!

Route::get('/', ['as' => 'home', function()
{
    dd(Request::exists('v'));
}]);


回答2:

tl;dr

Upgrade to Laravel 5.5 or higher. They changed this so now it works as you originally expected.

Explanation

In the Laravel 5.5 upgrade guide, we read the following:

The has Method

The $request->has method will now return true even if the input value is an empty string or null. A new $request->filled method has been added that provides the previous behavior of the has method.

The $request->exists method still works, it is just an alias for $request->has.

Examining the source code

  • In Laravel 5.4:
    • $request->exists: Determine if the request contains a given input item key.
    • $request->has: Determine if the request contains a non-empty value for an input item.
  • In Laravel 5.5:
    • $request->exists: Alias for $request->has
    • $request->has: Determine if the request contains a given input item key.
    • $request->filled: Determine if the request contains a non-empty value for an input item.

If you click to the commands above, you can check out the source code and see that they literally just renamed exists to has, has to filled, then aliased exists to has.



回答3:

You might wanna check this out. since the $request->has() method and it property can offer access to request origin.

It's ok to use $request->has('username') This will check if <input type="text" name="username" /> username attributes actually exist or the params/.query string actually have that key on the request global.



回答4:

As to me it's not a bug, but feature :) In your example v is provided, but it's empty.

In framework code you'll find this:

if ($this->isEmptyString($value)) return false;

So, if empty string is provided has() method will return false. It makes sense to me, in most cases I want this behavior.



回答5:

Use Request::filled() because unlike Request::has(), it also checks if the parameter is not empty.