Bald
Bald

Reputation: 2316

Request::has() returns false even when parameter is present

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?

Upvotes: 50

Views: 154344

Answers (5)

totymedli
totymedli

Reputation: 31126

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 behaviour of the has() method.

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

Examining the source code

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.

Upvotes: 86

Codedreamer
Codedreamer

Reputation: 1702

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.

Upvotes: 7

doncadavona
doncadavona

Reputation: 7760

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

Upvotes: 8

lukasgeiter
lukasgeiter

Reputation: 153030

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'));
}]);

Upvotes: 86

Limon Monte
Limon Monte

Reputation: 54419

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.

Upvotes: 3

Related Questions