Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 788
Bald Avatar asked Mar 23 '15 19:03

Bald


People also ask

What is request() In Laravel?

Laravel's Illuminate\Http\Request class provides an object-oriented way to interact with the current HTTP request being handled by your application as well as retrieve the input, cookies, and files that were submitted with the request.

Does laravel have request?

The has MethodThe $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.


3 Answers

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'));
}]);
like image 170
lukasgeiter Avatar answered Oct 21 '22 18:10

lukasgeiter


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

  • 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.

like image 45
totymedli Avatar answered Oct 21 '22 19:10

totymedli


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

like image 7
doncadavona Avatar answered Oct 21 '22 20:10

doncadavona