Search code examples
laravellaravel-validationlaravel-request

Using complex conditional validation rule in FormRequest in Laravel


I am developing a Web application using Laravel. What I am doing now is creating a FirmRequest for the validation.

This is my FormRequest.

use Illuminate\Foundation\Http\FormRequest;

class StoreVacancy extends FormRequest
{
    public function authorize()
    {
        return true;
    }

    public function rules()
    {
        return [
            'title' => 'required',
            'type' => 'required',
            'complex_field' => ...need complex conditional validation based on the type field
        ];
    }
}

If I did not use the FormRequest, I can create validator in the controller and set complex conditional validation rule like this.

$v = Validator::make($data, [
    //fields and rules
]);

$v->sometimes('reason', 'required|max:500', function ($input) {
    return $input->games >= 100;
});

But the issue is that I am not creating the Validator in the controller. But I am using the FormRequest. How can I achieve the same thing in the FormRequest?


Solution

  • You can manually adjust the rules depending on the input data:

    class StoreVacancy extends FormRequest
    {
        public function rules()
        {
            $reason = $this->request->get('reason'); // Get the input value
            $rules = [
                'title' => 'required',
                'type'  => 'required',
            ];
    
            // Check condition to apply proper rules
            if ($reason >= 100) {
                $rules['complex_field'] = 'required|max:500';
            }
    
            return $rules;
        }
    }
    

    Its not the same as sometimes, but it does the same job.