phplaravelvalidationconditional-statementsrules

Laravel: conditional validation rules


In my laravel application I need to apply the validation rules on conditional bases. For example: In the Store method the password field is required and min chars: 6. But, in Update method password field is not required, however, if the user enters the password then it must be greater than 6 chars.

SomeController.php

private function validations($customRules = [])
{
    # variables
    $rules = [
        'contact_person' => 'required|min:2',
        'mobile_number'  => 'required|numeric',
        'pword'          => 'required|min:6',
        'email'          => 'required|email',
        'address'        => 'required',
        'status'         => 'required',
    ];
    $messages = [
        'contact_person.required' => '`<strong class="style-underline">Contact person</strong>` - Required',
        'contact_person.min'      => '`<strong class="style-underline">Contact person</strong>` - Must be at least :min chars',

        'mobile_number.required' => '`<strong class="style-underline">Mobile number</strong>` - Required',
        'mobile_number.numeric'  => '`<strong class="style-underline">Mobile number</strong>` - Must be a numeric value',

        'email.required' => '`<strong class="style-underline">Eamil</strong>` - Required',
        'email.email'    => '`<strong class="style-underline">Email</strong>` - Must be a valid email address',

        'pword.required' => '`<strong class="style-underline">Password</strong>` - Required',
        'pword.min'      => '`<strong class="style-underline">Password</strong>` - Must have a at least :min characters',

        'status.required' => '`<strong class="style-underline">Status</strong>` - Required',
    ];

    if(!empty($customRules))
        $rules = \array_merge($rules, $customRules);

    # returning
    return request()->validate($rules, $messages);
}

After modifying the rules, based on the update method requirement, the pword field is validated for min chars. Which should not happen as the field was left empty.

Currently I am forced to do this.

public function update()
{
    ...

    # validating submitted data
    if(!empty(request()->pword))
        $this->validations([ 'pword' => 'min:6' ]);
    else
        $this->validations([ 'pword' => '' ]);

    ....
}

Solution

  • You can use nullabe instead required, Blank value converted as null if you are using eloquent, because of below middleware

        \Illuminate\Foundation\Http\Middleware\ConvertEmptyStringsToNull::class,
    

    So your method would be like

    private function validations($request,$update = false){
        $rules = [
            'contact_person' => 'required|min:2',
            'mobile_number'  => 'required|numeric',
            'pword'          => 'nullable|min:6',
            'email'          => 'required|email',
            'address'        => 'required',
            'status'         => 'required',
        ];
    
    }