Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

MrMooky's avatar

Adding error class to x-input

I haven't really touched Blade components for inputs and labels yet, as I've always encountered issues and went my usual way. But for a new project, I'd like to use a Blade component for input fields.

Whenever an error occurred with any input, I added the class error to it. Like so:

<input type="email" name="email" class="error">

I've been trying to figure out a way to use this in a component (without an actual PHP class).

As I can't simply do <x-input id="email" type="email" class="light @error('email') error @enderror" name="email" :value="old('email')" required />, I was wondering what a good way would be to append the error class to any invalid field.

I tried to pass the errors from the view into the component, like this:

<x-input id="email" type="email" class="light" :errors="$errors" name="email" :value="old('email')" required />

And then I wanted to use the array and find the field that needs the class.

Blade view:

<x-input id="email" type="text" class="light" field="email" :errors="$errors" name="email" :value="old('email')" required />

Component:

@props(['disabled' => false, 'errors', 'field'])

<input {{ $disabled ? 'disabled' : '' }} {!! $attributes->merge(['class' => 'field' . $errors->has($field) ? ' error' : '']) !!}> 

While that works, it feels wrong to send the full error bag into the component and also declare the field="email" in my view. I'd have to do that for every field.

What is the way to go here? There must be a simple method to append an error class, right?

0 likes
1 reply
Braunson's avatar
Braunson
Best Answer
Level 18

Here's how I currently do it, instead of passing the entire error bag, just pass the one for the field in question:

<x-input :error="$errors->first('state')">
@props([
    'error' => false
])

@if ($error)
    <div class="mt-1 text-red-500 text-sm">{{ $error }}</div>
@endif
1 like

Please or to participate in this conversation.