Mix blade and classic php syntax

I’m using the Laravel Collection HTML to create my form

I’ve created a service with some custom components inside a provider

class FormComponentServiceProvider extends ServiceProvider
{
    /**
     * Register services.
     *
     * @return void
     */
    public function register()
    {
        //
    }

    /**
     * Bootstrap services.
     *
     * @return void
     */
    public function boot()
    {
        $init = [
            'name',
            'label',
            'value' => null,
            'attributes' => [],
        ];
        Form::component('appText','components.form.text', $init);
        Form::component('appNumber','components.form.number', $init);
    }
}

I’ve created a number.blade.php called like this

{{ Form::appNumber('groupe_id', 'Groupe') }}

It’s working as expected so far. Now i’m doing the form validation. I want to add an error indication inside my input classes. I’ve done this so far

@error($name)
    @php $validation = 'is-invalid';@endphp
@else
    @php $validation = 'is-valid'; @endphp
@enderror
<div class="form-group">
    {{ Form::label($label, null, ['class' => 'control-label']) }}
    {{ Form::number($name, $value, array_merge(['class' => 'form-control ' . $validation], $attributes)) }}
</div>

But as you can see, the first 5 lines are quite heavy, so is it possible to do like a ternary condition ? knowing that it’s a mix of blade and classic PHP ?

I’m quite new to laravel, so there some aspect I still don’t get

>Solution :

Blade templates are always passed an $errors variable which is a message bag containing your errors. So just use that in an inline ternary statement:

<div class="form-group">
    {{ Form::label($label, null, ['class' => 'control-label']) }}
    {{ Form::number($name, $value, array_merge(['class' => 'form-control ' . ($errors->has($name) ? 'is-invalid' : 'is-valid')], $attributes)) }}
</div>

Leave a Reply