Questions & Answers

Laravel Livewire validation won't allow me to output dynamic field names

I have a Livewire component that contains a booking form. I have some dynamic form fields that are generated when a wired up button is pressed. The fields are displayed on the page by using array keys to make them unique:

     <label for="">Contact Phone</label>
        <input class="rounded border-gray-300 text-sm"
               name="attendee[{{ $key }}][contact_phone]">

Here are the validation rules inside the component controller:

            'course_date' => 'bail|required',
            'attendee' => 'array|required',
            'attendee.*.title' => 'required',
            'attendee.*.first_name' => 'required',
            'attendee.*.last_name' => 'required',
            'attendee.*.email' => 'required|email:rfc,dns',
            'attendee.*.contact_phone' => 'required|numeric|digits_between:10,13',
        ], [
            'course_date.required' => 'You must select a date.',
            'attendee.required' => 'Your booking must have at least one attendee.',
            'attendee.*.title.required' => 'Title cannot be blank.',
            'attendee.*.first_name.required' => 'First name cannot be blank.',
            'attendee.*.last_name.required' => 'Last name cannot be blank.',
            'attendee.*.email.required' => 'Please provide an email address.',
            'attendee.*' => 'Please provide a valid email address.',
            'attendee.*.contact_phone.required' => 'Please provide a contact phone number.',
            'attendee.*.contact_phone.numeric' => 'Please provide a valid phone number.',
            'attendee.*.contact_phone.digits_between' => 'Please provide a valid phone number.'

If I display the errors all together at the top of the form like this:

@if ($errors->any())
        <div class="alert alert-danger">
                @foreach ($errors->all() as $error)
                    <li>{{ $error }}</li>

they work fine, and if I display the errors for the nested fields like this:

    <span class="text-xs font-bold text-pink-900">{{ $message }}</span>

However if I want to do this so I can have it work dynamically:

 @error('attendee.{{ $key }}.title')
    <span class="text-xs font-bold text-pink-900">{{ $message }}</span>

it doesn't work. The error doesnt display at all.

2023-01-07 20:30:44
move the $key variable outside of the string and concatenate it with the string.
Answers(0) :