Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 858
Wai Yan Hein Avatar asked Nov 26 '25 00:11

Wai Yan Hein


2 Answers

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.

like image 93
thefallen Avatar answered Nov 28 '25 12:11

thefallen


Since 5.4 you can use the method "withValidator" inside your FormRequest: https://laravel.com/docs/5.4/validation

This method receives the fully constructed validator, allowing you to call any of its methods before the validation rules are actually evaluated

use Illuminate\Foundation\Http\FormRequest;

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

    public function rules()
    {
        return [
            'title' => 'required',
            'type' => 'required',
        ];
    }

    public function withValidator($validator)
    {
        $validator->sometimes('reason', 'required|max:500', function ($input) {
            return $input->games >= 100;
        });
    }
}
like image 31
atthakasem Avatar answered Nov 28 '25 12:11

atthakasem