79102292

Date: 2024-10-18 13:35:10
Score: 2
Natty:
Report link

I found a workaround for displaying validation error messages in my custom Livewire component. Here's how I approached it:

I created a custom component like this:

<div class="flex flex-col">
    <div class={{ $attributes->get('class') }}>
        {{-- Here I have my component --}}
        {{-- ... --}}
    </div>
    {{-- Here the errors --}}
    @foreach ($attributes as $key => $value)
        @if (str_starts_with($key, 'wire:model'))
            @error($value)
                <div class="text-red-500 text-sm mt-1 flex gap-2 items-center">
                    {{ $message }}
                </div>
            @enderror
        @endif
    @endforeach
</div>

When using the component, it looks like this:

<x-new-components.upload-button class="w-full" label="Driver's License" wire:model.defer="docs.drivers_license" />

The default structure of the $attributes array in the component has the following format:

#attributes: array:3 [
    "class" => "w-full",
    "label" => "Driver's License",
    "wire:model.defer" => "docs.drivers_license"
]

Essentially, I looped through the attributes to find the wire:model, allowing me to display the correct error message associated with it.

I know this may not be the best way to handle it, but it was the solution I found to avoid passing the error directly through the component. While this post is a bit dated, I hope this solution can help others facing a similar issue.

Reasons:
  • Long answer (-1):
  • Has code block (-0.5):
  • Me too answer (2.5): facing a similar issue
  • Low reputation (1):
Posted by: guiFerranti