Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Adding class conditionally inside Form::text() in Laravel Collective

Tags:

forms

php

laravel

I'm using Laravel Collective for my forms, and whenever the validation fails for a field, I need to add a class. The default field looks like this:

{{ Form::text('name', null, ['class' => 'form-control']) }}

Whenever validation fails, I need to add border-danger to the class:

{{ Form::text('name', null, ['class' => 'form-control border-danger']) }}

But I cannot simply do @if ($errors->has('name')) inside that {{ Form }} field.

Is there any simple way to accomplish this? One thing I don't want to do is somthing like this:

@if ($errors->has('name'))

{{ Form::text('name', null, ['class' => 'form-control border-danger']) }}

@else

{{ Form::text('name', null, ['class' => 'form-control']) }}

@endif
like image 635
Hardist Avatar asked Jul 21 '18 08:07

Hardist


1 Answers

You can use ternary operator like below

{{ Form::text('name', null, ['class' => 'form-control '.($errors->has('name') ? 'border-danger':'')]) }}

Use brackets to execute ternary operator first .

like image 81
Niklesh Raut Avatar answered Sep 22 '22 00:09

Niklesh Raut