wolfrogers
wolfrogers

Reputation: 21

Laravel validation if condition

I am trying to validate my field. If is_teacher is false and teacher_id is empty. then i will throw error message. But I am not sure why even if the is_teacher field is true they also prompt this error message. Suppose is_teacher is true, then no need enter this condition.

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);
}

Upvotes: 0

Views: 4334

Answers (2)

John Lobo
John Lobo

Reputation: 15319

is_bool check whether variable is boolean or not.Variable must be true or false for example

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

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

this will return true ;

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

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

this will return false.

If you see below function then you can see what exactly is_bool will do

/**
 * 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) {}

For more info : https://www.php.net/manual/en/function.is-bool.php

Updated

 $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);
    }

You can import valdiation and rule like below

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

Response will be

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

Upvotes: 2

Peppermintology
Peppermintology

Reputation: 10210

You can simplify your conditional down to the following:

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

Upvotes: 0

Related Questions