Ronnel Martinez
Ronnel Martinez

Reputation: 165

Laravel: Validation rules that depends on what the request is using condition

I just created a request using php artisan make:request MyExampleRequest and the next thing that I have to do is to have a logic where I can get the value from form input and compare it and choose which validation should the logic follow.

Inside the rules() method of MyExampleRequest.php, the logic would be like:

public function rules()
{
    if($valueFromPostInput === '2') {

        return [
            'email' => 'required|email',
            'confirm_email' => 'required|email|same:email',
            'g-recaptcha-response' => 'required|recaptcha'
        ];

    }

    return [
        'email' => 'required|email',
        'g-recaptcha-response' => 'required|recaptcha'
    ];
}

I tried this logic:

public function rules()
{
    if($this->attributes->has('valueFromPostInput') === '2') {
        // more codes... }
}

But that didn't work.

I know I can achive this one using the logic below inside the MyExampleController.php Controller:

public function create(Request $request)
{
    if($request->valueFromPostInput === '2') {
        $this->validate($request, [
            'email' => 'required|email',
            'confirm_email' => 'required|email|same:email',
            'g-recaptcha-response' => 'required|recaptcha'
        ]);
    } else {
        $this->validate($request, [
            'email' => 'required|email',
            'g-recaptcha-response' => 'required|recaptcha'
        ]);
    }
}

But I want that to happen in Request that I've made using php artisan make:request MyExampleRequest and use that in my controller like public function(MyExampleRequest $request).

I searched for the answer I cannot find any. I'd really appreciated your response.

PS: English is not my native language.

Upvotes: 2

Views: 1789

Answers (1)

apokryfos
apokryfos

Reputation: 40653

You could use the request helper:

public function rules()
{
    $baseRules = [
       'email' => 'required|email',
       'g-recaptcha-response' => 'required|recaptcha'
    ];
    if(request()->get("valueFromPost") === '2') {    
        return $baseRules + [                
            'confirm_email' => 'required|email|same:email'
        ];

    }

    return $baseRules;
}

Or the shorter (but less readable) version:

public function rules()
{
    return [
       'email' => 'required|email',
       'g-recaptcha-response' => 'required|recaptcha'
    ] + (request()->get("valueFromPost") === '2' ? [ 'confirm_email' => 'required|email|same:email' ] : []);    
}

Upvotes: 2

Related Questions