Search code examples
phplaravellaravel-bladeconditional-operator

Laravel blade set value on input with ternary if


I have a template that change the style if into an input is set the "value" attribute or not, even if it is empty.

For example this:

<input type="text" class="form-control" name="name" id="name" value="">

is different for the template from this:

<input type="text" class="form-control" name="name" id="name">

For this reason I need to check with a ternary if, if the value is set or not.

I wrote this code:

<input type="text" class="form-control" name="name" id="name" {{ (isset($category) ? ("value='".$category->name."'") : "") }}>

But when I run the page, and the $category variable is set, I find into the input a value like this: 'Category

I checked code generated and I can find this:

<input type="text" class="form-control" name="name" id="name" value="'Category" a="" name&#039;="">

But the value in the DB is Category name.

Could you please help me to find the issue?


Solution

  • I think a ternary operator it is not needed in this case, since you will do nothing in case condition result false.

    You can use just @if:

    @if (isset($category)) value="{{$category->name}}" @endif
    

    Also, there is an @isset directive, so could be more appropriate if you do:

    @isset($category) value="{{$category->name}}" @endisset 
    

    In your input

    <input type="text" class="form-control" name="name" id="name" @isset($category) value="{{$category->name}}" @endisset />
    

    Ref: Blade Directives If Statements.