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"
type="text"
name="attendee[{{ $key }}][contact_phone]">
Here are the validation rules inside the component controller:
$this->validate([
'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.*.email.email' => '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">
<ul>
@foreach ($errors->all() as $error)
<li>{{ $error }}</li>
@endforeach
</ul>
</div>
@endif
they work fine, and if I display the errors for the nested fields like this:
@error('attendee.0.title')
<span class="text-xs font-bold text-pink-900">{{ $message }}</span>
@enderror
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>
@enderror
it doesn't work. The error doesnt display at all.
$key
variable outside of the string and concatenate it with the string.