Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

vincent15000's avatar

Validation form request required_unless + exists

Hello,

I have this form validation rule.

'paymode_id' => 'required_unless:payment_date,null|exists:paymodes,id',

The problem is that event if the payment date is null, it checks for an existing paymode id.

Is it possible to check if the paymode id exists only if the payment date is not null ?

Thanks for your help.

V

0 likes
5 replies
MichalOravec's avatar

What about like this?

'paymode_id' => $request->has('payment_date')
	? 'required_unless:payment_date,null|exists:paymodes,id'
    : 'required_unless:payment_date,null',
1 like
MichalOravec's avatar
Level 75

@vincent15000 Or

'paymode_id' => [
    'required_unless:payment_date,null',
    Rule::when($request->has('payment_date'), fn () => Rule::exists('paymodes')),
],
1 like
vincent15000's avatar

Lary AI suggested me to create a custom Rule with a passes function, but a rule has a validate function.

I solved my problem like this.

public function validate(string $attribute, mixed $value, Closure $fail): void
{
    $payment_date = request()->payment_date;

    if ($payment_date && !Paymode::where('id', $value)->exists()) {
        $fail('Le mode de paiement choisi n\'existe pas.');
    }
}
MichalOravec's avatar

@vincent15000 When you need to include an apostrophe (') in a string, use double-quotes.

$fail("Le mode de paiement choisi n'existe pas.");
1 like

Please or to participate in this conversation.