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?
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?
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'));
}]);
Upgrade to Laravel 5.5 or higher. They changed this so now it works as you originally expected.
In the Laravel 5.5 upgrade guide, we read the following:
The
has
MethodThe
$request->has
method will now returntrue
even if the input value is an empty string ornull
. A new$request->filled
method has been added that provides the previous behavior of thehas
method.
The $request->exists
method still works, it is just an alias for $request->has
.
$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.$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
.
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.
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.
Use Request::filled()
because unlike Request::has()
, it also checks if the parameter is not empty.