Laravel Blade question: how do you dynamically set the field name for @error directive within a component

Viewed 17

Fairly basic question as I'm going back to webdev after a few years away so experimenting.

I want to create a reusable component that wraps an error message in a formatted element:

I'd call it in my partial as...

<x-error :blah="$woof"/>

The component code would be something like this:

@error('field') "nicely formatted message" @enderror

However, I want to be able to dynamically set the field name within for the error directive, something like:

@error($field) or @error({{ $field }}) "nicely formatted message" @enderror

...while in the executing partial it would be called through something like:

<x-error :field='email'> or <x-error :field='password'> or <x-error :field='description'> or whatever field name you like.

After spending way too long trawling the web for clues I'm starting to suspect this isn't possible.

Is it? If so how do you do it? Any help or clues gratefully received

Cheers!

1 Answers

The answer is embarrassingly simple: leave off the semicolon! The semicolon kinda acts like a pointer to a variable, rather than passing the data directly to the component, so instead of:

<x-error :field="$title" />

It should be :

<x-error field="title" />

In the component you merely call the variable name:

@error($field)

"nicely formatted message"

@enderror

Easy, init?

Related