mrhn
mrhn

Reputation: 18936

Generate dynamic css classes in laravel-blade

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
">

Upvotes: 7

Views: 20092

Answers (4)

Justin Russell
Justin Russell

Reputation: 1103

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')),
])>

Upvotes: 0

Francis
Francis

Reputation: 31

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) }}">

Upvotes: 3

Jilson Thomas
Jilson Thomas

Reputation: 7303

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.

Upvotes: 20

Wistar
Wistar

Reputation: 3790

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

Upvotes: 2

Related Questions