Validation can';t使用布尔验证laravel 5

Validation can';t使用布尔验证laravel 5,validation,laravel,laravel-5,boolean,laravel-5.2,Validation,Laravel,Laravel 5,Boolean,Laravel 5.2,我使用的是Laravel 5.2,正如文档所述: 布尔值 验证中的字段必须能够转换为布尔值。接受的输入为真、假、1、0、“1”和“0” 所以我创建了一个,打开时返回true,关闭时返回false。刀锋在这里: {!! Form::hidden('eh_capa', 0) !!} Want to select as a graph cover? <label> Off <input name="cover" type="checkbo

我使用的是Laravel 5.2,正如文档所述:

布尔值

验证中的字段必须能够转换为布尔值。接受的输入为真、假、1、0、“1”和“0”

所以我创建了一个,打开时返回true,关闭时返回false。刀锋在这里:

{!! Form::hidden('eh_capa', 0) !!}
Want to select as a graph cover?
<label>
    Off
    <input name="cover" type="checkbox" checked>
    <span class="lever"></span>
    on
</label>
dd()函数返回我的请求,如下所示:

StoreGraficoPostRequest {#441 ▼
  #container: Application {#3 ▶}
  #redirector: Redirector {#448 ▶}
  #redirect: null
  #redirectRoute: null
  #redirectAction: null
  #errorBag: "default"
  #dontFlash: array:2 [▶]
  #json: null
  #convertedFiles: array:1 [▶]
  #userResolver: Closure {#355 ▶}
  #routeResolver: Closure {#354 ▶}
  +attributes: ParameterBag {#443 ▶}
  +request: ParameterBag {#440 ▼
    #parameters: array:5 [▼
      "_token" => "bZIpGW6UCcYHlCTZuIZMtmOrpCodWyfcbO1HgQid"
      "path" => "hello.pdf"
      "cover" => 1
      "obra_id" => "29"
      "arquivo" => UploadedFile {#438 ▶}
    ]
  }
  +query: ParameterBag {#442 ▶}
  +server: ServerBag {#446 ▶}
  +files: FileBag {#445 ▶}
  +cookies: ParameterBag {#444 ▶}
  +headers: HeaderBag {#447 ▶}
  #content: ""
  #languages: null
  #charsets: null
  #encodings: null
  #acceptableContentTypes: null
  #pathInfo: null
  #requestUri: null
  #baseUrl: null
  #basePath: null
  #method: "POST"
  #format: null
  #session: Store {#394 ▶}
  #locale: null
  #defaultLocale: "en"
}

但是当我对dd函数进行注释时,验证返回的cover必须是true或false。如果启用时将cover字段的值更改为true、“1”和“true”,也会发生同样的情况。我在网上搜索了所有有帮助的东西,但一无所获。。。我开始认为这是一个Laravel bug…

您在错误的位置修改输入。您应该重写请求类中的all()函数,并在那里修改您的输入

public function rules()
{
    return [
        'cover' => 'required|boolean',
        'obra_id' => 'exists:obras',
        'path' => 'required',
        'arquivo' => 'required|file|max:2048|mimes:pdf',
    ];
}

public function all()
{
    $input = parent::all();

    $input['cover'] = $input['cover'] === 'on' ? 1 : 0;
    $input['obra_id'] = ...
    $input['arquivo'] = ...

    return $input;
}

嗯,我有办法做到。诀窍就是将以下代码添加到我的请求类:

protected function getValidatorInstance()
{
    $data = $this->all();
    $data['eh_capa'] = $data['eh_capa'] === 'on' ? 1 : 0;
    $data['obra_id'] = $this->route('obra');
    $this->getInputSource()->replace($data);

    /* modify data before send to validator */

    return parent::getValidatorInstance();
}

然后,我的rules方法只以return结束。

我遇到了同样的问题,决定创建一个小型静态类,解析规则中标记为boolean的所有值

其优点是,它只解析规则规定为布尔值的布尔值。任何其他输入值都将保持不变,如果需要,仍然可以发布一个值为“true”的字符串

<?php

namespace App\Helpers;

use Illuminate\Http\Request;
use Illuminate\Support\Facades\Validator;

class ValidationHelper {

    /**
    * A recursive funciton to loop over any input and parse them to true booleans.
    */
    private static function _getObj(&$inputs, $idPath) {
        $idPart = array_shift($idPath);

        if (count($idPath) > 0) {
            if ($idPart == '*') {
                for ($i = 0; $i < count($inputs); $i++) {
                    ValidationHelper::_getObj($inputs[$i], $idPath);
                }
            }
            else {
                ValidationHelper::_getObj($inputs[$idPart], $idPath);
            }
        }
        else {
            $currentValue = $inputs[$idPart];
            if ($currentValue == 1 || strtolower($currentValue) == 'true') {
                $inputs[$idPart] = true;
            }
            else if ($currentValue == 0 || strtolower($currentValue) == 'false') {
                $inputs[$idPart] = false;
            }
            else {  // any other value will be left untouched
                $inputs[$idPart] = $currentValue;
            }
        }
    }

    /**
    * Will validate a request against the given rules.
    * Will also help fix any booleans that otherwise are parsed as 'true' strings.
    * @param Request $request   
    * @param Array $rules       
    * @return void
    */
    public static function validateRequest(Request $request, $rules) {
        // Find any rules demanding booleans:
        $booleanIDs = [];
        foreach ($rules as $id => $rule) {
            if (is_string($rule)) {
                $rule = explode('|', $rule);
            }
            if (in_array('boolean', $rule)) {
                $booleanIDs[] = $id;
            }
        }

        if (isset($booleanIDs)) {
            // Set all inputs to a bindable array:
            $inputs = [];
            foreach ($request->all() as $key => $value) {
                $inputs[$key] = $value;
            }

            // Recursively loop through the boolean-ids
            foreach ($booleanIDs as $id) {
                $idPath = explode('.', $id);
                ValidationHelper::_getObj($inputs, $idPath);
            }

            // Make sure the booleans are not just validated correctly but also stay cast when accessing them through the $request later on.
            $request->replace($inputs);
        }
        else {
            $inputs = $request->all();
        }

        $validator = Validator::make($inputs, $rules);
        if ($validator->fails()) {
            throw new \Exception('INVALID_ARGUMENTS', $validator->errors()->all());
        }
    }

}

这不是一只拉威尔虫子。我在使用laravel 5.2的当前项目中使用布尔验证。您在验证规则内设置请求值的原因是什么?不,没有原因。。。我试图强迫他们出现在我的请求中以验证。。。但我认为@sameeranand1改变了我的观点。@ThalesNathan的
$this->['field']
实际上是一种get mutator,你不能这样改变它的值;)此父级:all()似乎不起作用。。。你不认为它是$this->all()吗?好的,我知道了,我使用了parent::all()而不是parent:all(),现在我的请求被拒绝了(它返回了一个ERR\u CONNECTION\u RESET)。如果我评论all方法override,它会处理我之前发布的相同问题。对不起,这是我的错别字。是的,它是parent::all()。这不应导致错误连接重置。我不太确定这是从哪里来的。没关系,我想出了一个办法!我会把它寄出去
<?php

namespace App\Helpers;

use Illuminate\Http\Request;
use Illuminate\Support\Facades\Validator;

class ValidationHelper {

    /**
    * A recursive funciton to loop over any input and parse them to true booleans.
    */
    private static function _getObj(&$inputs, $idPath) {
        $idPart = array_shift($idPath);

        if (count($idPath) > 0) {
            if ($idPart == '*') {
                for ($i = 0; $i < count($inputs); $i++) {
                    ValidationHelper::_getObj($inputs[$i], $idPath);
                }
            }
            else {
                ValidationHelper::_getObj($inputs[$idPart], $idPath);
            }
        }
        else {
            $currentValue = $inputs[$idPart];
            if ($currentValue == 1 || strtolower($currentValue) == 'true') {
                $inputs[$idPart] = true;
            }
            else if ($currentValue == 0 || strtolower($currentValue) == 'false') {
                $inputs[$idPart] = false;
            }
            else {  // any other value will be left untouched
                $inputs[$idPart] = $currentValue;
            }
        }
    }

    /**
    * Will validate a request against the given rules.
    * Will also help fix any booleans that otherwise are parsed as 'true' strings.
    * @param Request $request   
    * @param Array $rules       
    * @return void
    */
    public static function validateRequest(Request $request, $rules) {
        // Find any rules demanding booleans:
        $booleanIDs = [];
        foreach ($rules as $id => $rule) {
            if (is_string($rule)) {
                $rule = explode('|', $rule);
            }
            if (in_array('boolean', $rule)) {
                $booleanIDs[] = $id;
            }
        }

        if (isset($booleanIDs)) {
            // Set all inputs to a bindable array:
            $inputs = [];
            foreach ($request->all() as $key => $value) {
                $inputs[$key] = $value;
            }

            // Recursively loop through the boolean-ids
            foreach ($booleanIDs as $id) {
                $idPath = explode('.', $id);
                ValidationHelper::_getObj($inputs, $idPath);
            }

            // Make sure the booleans are not just validated correctly but also stay cast when accessing them through the $request later on.
            $request->replace($inputs);
        }
        else {
            $inputs = $request->all();
        }

        $validator = Validator::make($inputs, $rules);
        if ($validator->fails()) {
            throw new \Exception('INVALID_ARGUMENTS', $validator->errors()->all());
        }
    }

}
    ValidationHelper::validateRequest($request, [
            ['foo'] => ['nullable', 'boolean'],
            ['bar'] => ['required', 'boolean'],
            ['item.*.isFoo'] => ['nullable', 'boolean'],
            ['item.*.isBar'] => 'required|boolean'],
        ]);