Conditional Attributes

Conditional Classes, Styles, and Attributes

@class([...]) keeps a keyed class only when its value is true; @style([...]) does the same for declarations. @checked, @selected, @disabled, @readonly and @required print their bare attribute when the argument is true, which ends <?php if ($x) echo 'selected'; ?> clutter:

The form in resources/views/products/search.blade.phpHTML
<select name="category">
  @foreach ($categories as $value => $label)
    <option value="{{ $value }}" @selected($value === $selected)>{{ $label }}</option>
  @endforeach
</select>
<label><input type="checkbox" name="in_stock" @checked($inStockOnly)> In stock only</label>
<input type="search" name="q" placeholder="Title or author" @required(true)>
<button @class(['secondary' => ! $inStockOnly]) @disabled(empty($categories))>Search</button>
Output
$ curl -s localhost:8306/search | grep -E 'selected|checked|required|<button'
              <option value="tech" selected>Technology</option>
    <label><input type="checkbox" name="in_stock" checked> In stock only</label>
    <input type="search" name="q" placeholder="Title or author" required>
    <button class="" >Search</button>

With every condition false, @class still prints a harmless class="". Blade keeps the indentation of directive lines, so its HTML is valid rather than tidy.