Laravel `required` validator does not work for empty string

I am trying to use the laravel requiredvalidator in my code, unfortunately, it does not work even for an empty string. I do not want this to happen due to an empty string.

$validator = \Validator::make(array("name"=>""), array("name"=>"required"));
if ($validator->fails()){
    var_dump($validator->messages());
} else {
    die("no errors :)");
}

He gives me the following conclusion

object(Illuminate\Support\MessageBag)[602]
  protected 'messages' => 
    array (size=1)
      'name' => 
        array (size=1)
          0 => string 'The name field is required.' (length=27)
  protected 'format' => string ':message' (length=8)

It should pass, since I give an empty string as a field name.

The above behavior occurs in the OSX environment (PHP version 5.5.18), but works fine in the linux environment (PHP version 5.5.9-1ubuntu4.5).

+6
source share
3 answers

The rule requiredactually returns false if you pass an empty string.

If we look at the code ( Illuminate\Validation\Validator)

protected function validateRequired($attribute, $value)
{
    if (is_null($value))
    {
        return false;
    }
    elseif (is_string($value) && trim($value) === '')
    {
        return false;
    }

    // [...]

    return true;
}

, - , , null:

Validator::extendImplicit('attribute_exists', function($attribute, $value, $parameters){
    return ! is_null($value);
});

( extendImplicit, extend , )

:

\Validator::make(array("name"=>""), array("name"=>"attribute_exists"));
+11

:

'my_field' => 'present'  
+3

Laravel 5.6 :

public function rules()
{
    return [
        'my_field' => 'required|string|nullable'
    ];
}

, 5.6

+2

All Articles