首页 > 解决方案 > Laravel 验证条件

问题描述

我正在尝试验证我的领域。如果 is_teacher 为 false,teacher_id 为空。然后我会抛出错误信息。但我不确定为什么即使 is_teacher 字段为真,它们也会提示此错误消息。假设 is_teacher 为真,则无需输入此条件。

if(is_bool($input['is_teacher']) == false && empty($input['teacher_id'])) {
   $validator->errors()->add('teacher_id', 'Please select a teacher.');
   return response()->json([
      'error'    => true,
      'messages' => $validator->errors(),
   ], 422);
}

标签: phplaravel

解决方案


is_bool 检查变量是否为布尔值。变量必须是truefalse 例如

$input=['is_teacher'=>true];

dd(is_bool($input['is_teacher']));

这将返回 true ;

$input=['is_teacher'=>12];

    dd(is_bool($input['is_teacher']));

这将返回错误。

如果你看到下面的函数,那么你可以看到 is_bool 到底会做什么

/**
 * Finds out whether a variable is a boolean
 * @link http://php.net/manual/en/function.is-bool.php
 * @param mixed $var <p>
 * The variable being evaluated.
 * </p>
 * @return bool true if var is a boolean,
 * false otherwise.
 * @since 4.0
 * @since 5.0
 */
function is_bool ($var) {}

欲了解更多信息:https ://www.php.net/manual/en/function.is-bool.php

更新

 $input=[
        'is_teacher'=>0,
        'teacher_id'=>""
    ];
    $validator = Validator::make($input, [
        'teacher_id' => Rule::requiredIf(function () use ($input) {
            return !$input['is_teacher'] && empty($input['teacher_id']);
        }),

    ],[
        'teacher_id.required'=>'Please select a teacher.'
    ]);

    if ($validator->fails()) {
        return response()->json([
            'error' => true,
            'messages' => $validator->errors(),
        ], 422);
    }

您可以像下面这样导入验证和规则

use Illuminate\Support\Facades\Validator;
use Illuminate\Validation\Rule;

回应将是

{
"error": true,
"messages": {
"teacher_id": [
"Please select a teacher."
]
}
}

推荐阅读