how to put @error class on laravelcollective

Viewed 1749

i just install laravelcollective 5.8 and try to put error class on input form like this

{{Form::number('nik', '', ['id'=>'nik','min'=>'1','max'=>'999999','class'=>'form-control @error('nik') is-invalid @enderror','placeholder'=>'E.g: 1234','required'])}}

first i got error

syntax error, unexpected 'nik' (T_STRING), expecting ']'

and i try to change @error('nik') to @error("nik") , but no luck, this what happen on inspect element

<input id="nik" min="1" max="999999" class="form-control <?php if ($errors->has(&quot;nik&quot;)) :
if (isset($message)) { $messageCache = $message; }
$message = $errors->first(&quot;nik&quot;); ?> is-invalid <?php unset($message);
if (isset($messageCache)) { $message = $messageCache; }
endif; ?>" placeholder="E.g: 1234" required="" name="nik" type="number" value="">

this how should be on native laravel blade

<input required min="1" max="999999" id="nik" class="form-control @error('nik') is-invalid @enderror" type="number" name="nik" placeholder="E.g: 1234">

and inspect element will be :

<input required="" min="1" max="999999" id="nik" class="form-control " type="number" name="nik" placeholder="E.g: 1234">

anyone know how to solve this, i'll so greatfull.. thank you...

2 Answers

Everything within the {{ }} is PHP, not Blade, so a directive like @error won't work in there.

{{ Form::number('nik', '', [
    'id'=>'nik',
    'min'=>'1',
    'max'=>'999999',
    'class'=>'form-control @error('nik') is-invalid @enderror',
    'placeholder'=>'E.g: 1234',
    'required'
]) }}

Instead, do it the PHP way:

'class' => 'form-control' . ($errors->has('nik') ? ' is-invalid' : null),

You could also create a helper function and make use of the shared errors variable in the view.

function add_error($name, $error_class = ' is-invalid ')
{
    $errors = view()->shared('errors');

    return $errors && $errors->has($name) ? $error_class : '';
}

And append that to the class.

{{ Form::text('name', null, [
    'id'=>'name',
    'class'=>'form-control' . add_error('name'),
    'placeholder'=>'Name',
    'required'
]) }}
Related