MrMooky's avatar

Reset model if validation fails

I have a public property called $logo;. I also have two validations in place: mimes and max. When a validation fails, e.g. the image format is not supported or the image is too big, the component still renders the $logo property and generates the temporaryUrl().

That seems kind of wrong. So if the image upload would fail, I don't want to image to be shown. How could I prevent that?

So the following is rendered on updated, even though the validation fails correctly.

@if ($logo)
    <div class="image__preview">
        <img src="{{ $logo->temporaryUrl() }}" alt="" width="150">
    </div>
@endif

Also, due to the nature of the HTML file field, the selected file-input is not being reset when validation fals. But I think I have to do that manually with browser events, right?

0 likes
7 replies
Snapey's avatar
Snapey
Best Answer
Level 122

perhaps only show the logo if $logo is set AND there are no validation errors

MrMooky's avatar

@Snapey Ah yes, this seems to work the way I wanted:

@if ($logo)
    @error('logo')
        nope
    @else
        <div class="image__preview">
            <img src="{{ $logo->temporaryUrl() }}" alt="" width="150">
        </div>
    @enderror
@endif

And yes, I am not able to reset or set to null with the default Livewire validation. So I guess I'll go with dispatching a browser event to clear the file-input.

Snapey's avatar

@MrMooky the file input control is immutable so you have to trick livewire into re-rendering it as per my link

MrMooky's avatar

@Snapey Hm, that only seems to work when I choose images. The iteration is counted up. But when I select some file that is not supported, e.g. a xml file, the validator kicks in, but is not updating the iteration. Really odd. o_O

public function updated()
{
    $this->iteration++;
        
    $this->validate();
}
Snapey's avatar

@MrMooky ok so another option is to just use a random number in the blade view. This will cause the file input to be re-rendered on every livewire render

MrMooky's avatar

@Snapey That also resets the field when an allowed and valid file is attached. The actual upload is not happening via Livewire, but a regular Controller action. So the request does not have the property of the logo when it is being reset.

I might just implement a second validation in the controller and skip the upload if the validation fails.

Please or to participate in this conversation.