Laravel $request->has('name') doesn't work

10,230

Solution 1

If you are not using SanitizeMiddleware laravel will keep the input name as property in the request as an empty string ("") so ->has("name") method will return true always.

Do the following, on console:

php artisan make:middleware SanitizeMiddleware

Then fill the new Middleware

   <?php

namespace App\Http\Middleware;

use Closure;

class SanitizeMiddleware
{
    /**
     * Handle an incoming request.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \Closure  $next
     * @return mixed
     */
    public function handle($request, Closure $next)
    {
        foreach ($request->input() as $key => $value) {
            if (empty($value) || $value == "") {
                if($value !== '0')
                $request->request->remove($key);
            }
        }

        return $next($request);
    }
}

And register it on Kernel, within the web middleware group or wherever yo want to use it:

    /**
 * The application's route middleware groups.
 *
 * @var array
 */
protected $middlewareGroups = [
    'web' => [
        \App\Http\Middleware\EncryptCookies::class,
        \Illuminate\Cookie\Middleware\AddQueuedCookiesToResponse::class,
        \Illuminate\Session\Middleware\StartSession::class,
        \Illuminate\View\Middleware\ShareErrorsFromSession::class,
        \App\Http\Middleware\VerifyCsrfToken::class,
        \Illuminate\Routing\Middleware\SubstituteBindings::class,
        SanitizeMiddleware::class,
    ],

    'api' => [
        'throttle:60,1',
        'bindings',
    ],
];

This will remove empty inputs from incoming request so ->has("") should work now.

Solution 2

You should just be able to test if the nombre property of the request object is a falsy value (ie. does not exist, is empty, or is null) by:

if($request->nombre) {
    //do something
} else {
    //do something else
}

Solution 3

Read Laravel docs attentively, for proper usage of the HTTP Requests.

Determining If An Input Value Is Present

You should use the has method to determine if a value is present on the request. The has method returns true if the value is present on the request:

if ($request->has('name')) {
    //
}

If you would like to determine if a value is present on the request and is not empty, you may use the filled method:

if ($request->filled('name')) {
    //
}
Share:
10,230

Related videos on Youtube

FranRP
Author by

FranRP

Updated on June 04, 2022

Comments

  • FranRP
    FranRP almost 2 years

    I recently started using laravel to learn how to use it. Currently, I am handling forms and looking at the different methods that Laravel offers to facilitate our work but I can not see why the following code does not work:

    public function mensajes(Request $request) {
        //return $request->all();
    
        if ($request->has('nombre')){
            return "Sí tiene nombre. Es ". $request->input('nombre') ." y su correo es ". $request->input('email');
        } else {
            return "No tiene nombre";
        }
    
    
    
    }
    

    I try to verify that the form receives the input "name", but it receives it or not, it takes it as if it existed and if it was filled, however, when trying to execute this code if it does it correctly.

    public function mensajes(Request $request) {
        //return $request->all();
    
        if ($request->input('nombre') != ''){
            return "Sí tiene nombre. Es ". $request->input('nombre') ." y su correo es ". $request->input('email');
        } else {
            return "No tiene nombre";
        }
    
    
    
    }
    

    I have a lot, maybe too much time watching my code, without seeing the error.

    • Mahdi Younesi
      Mahdi Younesi about 6 years
      has checks if input exists in request array or not
    • FranRP
      FranRP about 6 years
      But I have seen how they use it to check whether or not the input field has value, that is, if nothing is entered in that field of the form, I should make the second return of my code, but it does not work that way.
    • Mahdi Younesi
      Mahdi Younesi about 6 years
      thats if ($reques->get('name') !== null)
    • FranRP
      FranRP about 6 years
      I know it can be done in other ways, so I put the second code which works and does what I want, but I want to understand the use of has and because it does not work for me in the same way as the rest. If Has not do what I want, it will be version problems maybe