Home > Mobile >  Validating old method in control does not work correctly with empty value
Validating old method in control does not work correctly with empty value

Time:08-11

In laravel 9, breeze form I use old method in controls like :

<x-input id="text" type="text" name="text" value="{{old('text') ? old('text') : $subscription->text }}" />
...
<input type="checkbox" @if (old('published') ? old('published') : $subscription->published) checked @endif

But it does not work correctly in case when in text input I leave empty text and I leave published field unchecked :

text input shows $subscription->text(If it had some content from db) and published checkbox is checked (If ($subscription->published) was checked priorly from db)

How can it be fixed ?

Thanks!

CodePudding user response:

The checkbox works differently then other inputs.

If checkbox is unchecked, it always get null in old('published').

Now to fix that, we need 2 condition.

@php
    $checked = '';
    if (count($errors)) {
        $checked = old('published') ? "checked=''" : '';
    } elseif ($subscription->published) {
        $checked = "checked=''";
    }
@endphp
<input type="checkbox" {{ $checked }} .../>

First condition will check, is there any errors. If yes, then it will alway get value from old('published').

  • Related