7

I'm in a classical scenario where i want based on wheter an error has occurred or not to change the css classes. As shown below, where has-error should change accordingly.

<div class="form-group has-error">

The project is in Laravel, where we mainly want to do everything in Blade as of now, we came up with the following solution which works, but does not look pretty or intuitive at all, so the question is, is there a more optimal way of doing this?

<div class="form-group
@if($errors->has('email'))
        has-error
@endif
">

4 Answers 4

20

Try the if else condition short hand code:

<form class="form-group {{ $errors->has('email') ? 'has-error' : '' }}">

This seems neat.

Even the Laravel 5.2 auth forms are done this way.

Sign up to request clarification or add additional context in comments.

1 Comment

Neat tryed a similar apporach, but the compiler kept puking at me, will try this version when i get to the office, thanks this is definetly in the range of pretty enough
3

You can make use of arrays to store the class names

@php
$formGroupClasses = ['form-group'];

if ($errors->has('email')) {
  $formGroupClasses[] = 'has-error';
}
@endphp

and then implode them to create a string

<form class="{{ implode(' ', $formGroupClasses) }}">

Comments

2

That's what I do. You could also do it that way:

@if($errors->has('email'))
    <div class="form-group has-error"> 
       //You can also edit classes of other elements 
    </div>
@else
    <div class="form-group"></div>
@endif

1 Comment

Also the same conclusion i came up with, but missing an ng-class like AngularJS has.
0

It's obviously been a bit since this question was asked, but these days you can clean things up a bit with conditional classes:

<div @class([
    'form-group',
    'has-error' => $errors->has('email')),
])>

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.