Home > database >  Laravel anonymous component with an if statement
Laravel anonymous component with an if statement

Time:11-10

So I wish to create the following simple thing. I have a simple input field in an anonymous component, and I am using the following code:

<x-form.input.text :error="$errors->first('name')"
                   field="name"
                   required="required" {!! isset($something) ? 'autofocus="autofocus"' : '' !!}/>

If $something exists, then autofocus="autofocus" should be added. And if not, nothing should be added.

But when using the above code, my whole input disappears. And in my source code, instead of seeing the input field, I see the blade code as follows:

<x-form.input.text :error="$errors->first('name')"
                   field="name"
                   required="required" autofocus="autofocus"/>

While it should of course be:

<input name="name" type="text" value="test" required="required" autofocus="autofocus">

My main question is, I would like to understand why this happens and I cannot use this piece of code inside the anonymous component:

{!! isset($something) ? 'autofocus="autofocus"' : '' !!}

Second but less importantly, a fix would be nice.

CodePudding user response:

In order to fix your code to use autofocus, you can make use of @props (documentation)

You can check the following code of the anonymous component:

@props(['autofocus'])

<input {{ $attributes->merge(['autofocus' => $autofocus]) }}/>

Whenever you call it like this:

<x-input name="input" type="text" required="true" autofocus="true"></x-inpout>

it will autofocus.

  • Related