What might be the best way for determining the first invalid input field in a flash error list in order to set the autofocus on that input field. By default, Laravel Breeze places the autofocus on the first field of the registration form, but I would like to have it so that autofocus is placed on the first invalid field in the form. To do this, I modified the existing input field component (x-input) to accept an autofocus property.
@props(['disabled' => false, 'autofocus' => false])
<input {{ $disabled ? 'disabled' : '' }} {{ $autofocus ? 'autofocus' : '' }} {!! $attributes->merge(['class' => 'rounded-md shadow-sm border-gray-300 focus:border-tlabTertiary focus:ring focus:ring-tlabTertiary']) !!}>
I then use raw php directives to determine whether the field’s input is invalid, set a flag variable to true/false accordingly, and then send this variable to the input component.
<form method="POST" action="{{ route('register') }}">
@csrf
<!-- Name -->
<div>
@php
$autofocus = false;
if ($errors->has('name') || !$errors->any()) {
$autofocus = true;
}
@endphp
<x-label for="name" :value="__('Name')" />
<x-input id="name" class="block mt-1 w-full" type="text" name="name" :value="old('name')" :autofocus='$autofocus' />
<x-input-error field="name" />
</div>
<!-- Email Address -->
<div class="mt-4">
@php
$autofocus = false;
if ($errors->has('email')) {
$autofocus = true;
}
@endphp
<x-label for="email" :value="__('Email')" />
<x-input id="email" class="block mt-1 w-full" type="email" name="email" :value="old('email')" required :autofocus='$autofocus' />
<x-input-error field="email" />
</div>
// ...
</form>
The $errors variable will tell you what the first error message is, but I'm not sure if it can tell you which input field it pertains to.
$errors->first('email')
There is surely a more elegant solution than the one I've come up with, perhaps using Livewire or Alpine? Or does Blade have an autofocus feature that I'm unaware of?