Laravel blade - Add a class if a condition is met
Asked Answered
E

7

33

This is simple but I can't seem to be able to do it with blade and I usually go back to php for this but, since I can't declare a new php variable with blade (without printing it, that is) how should I change a simple class name if a certain condition is met? Take this example of a link, I just want to add the class "active" if $hostess->active=1

 {{ HTML::linkRoute('hostesses.index', 'Archived', $params, array('class' => 'btn btn-default')) }}

I know how to do this with php, but how would it be done with blade?

Etra answered 30/4, 2014 at 8:11 Comment(0)
D
10

Something like this?

{{ HTML::linkRoute('hostesses.index', 'Archived', $params, array('class' => $hostess->active ? 'btn btn-info' : 'btn btn-default')) }}
Dettmer answered 30/4, 2014 at 8:20 Comment(0)
Z
42

You could do this:

// App/Http/routes.php
Route::get('foo/bar', 'FooController@bar);
// Your blade file
<li class="{{ Request::path() ==  'foo/bar' ? 'active' : ''  }}">
    <a href="{{ url('foo/bar') }}"></i> Bar</a>
</li>
Zawde answered 28/11, 2015 at 18:58 Comment(1)
Perfect for layout extendsPerforming
F
20

Now we can use conditional classes with @class directive like this

@php
    $isActive = false;
    $hasError = true;
@endphp

<span @class([
    'p-4',
    'font-bold' => $isActive,
    'text-gray-500' => ! $isActive,
    'bg-red' => $hasError,
])></span>

https://laravel.com/docs/8.x/blade#conditional-classes

Finback answered 1/11, 2021 at 3:14 Comment(1)
seems it doesn't work with $loop variableBethany
C
11

There is also another option:

<li class="@if(Request::is('/')) is-active @endif">
    <a href="{{ route('index') }}">Home</a>
</li>
Coachwork answered 10/6, 2020 at 15:41 Comment(0)
D
10

Something like this?

{{ HTML::linkRoute('hostesses.index', 'Archived', $params, array('class' => $hostess->active ? 'btn btn-info' : 'btn btn-default')) }}
Dettmer answered 30/4, 2014 at 8:20 Comment(0)
B
3

Here's a much more clear way to do that. Which should match the route name.

request()->routeIs('admin.cities')
Balcke answered 4/4, 2021 at 17:39 Comment(1)
this is the best approach, especially when you have variable or locale in your pathScarlettscarp
S
0

If you have a parameter in your query, then you could do something like this:

Your URL: https://www.yourdomain.com/a=dark 

// Your blade file
<li class="{{ Request::get('a') ==  'dark' ? 'active' : ''  }}">
    <a href="{{ url('foo/bar') }}"></i> Bar</a>
</li>
Sudiesudnor answered 2/10, 2022 at 20:34 Comment(0)
C
0

This is another way that you can try!

<li class="{{ Route::has('login') ? 'bg-dark' : ''  }}"></li>
Cioffred answered 1/3, 2023 at 12:40 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.