How to Add Active Class Dynamically in Laravel 11

Websolutionstuff | Jul-08-2024 | Categories : Laravel Bootstrap

Hello, laravel web developers! In this article, we'll see how to add an active class dynamically in laravel 11. Here, we'll learn about adding an active class on the active menu in laravel 11. You can add an active class on an active URL in laravel 11.

Add active class to a navigation menu based on URL.

Laravel 11 Active Menu Example

laravel active menu

 

Step 1: Add Routes

In this step, we'll define the routes into the web.php file.

routes/web.php

Route::get('/home', 'HomeController@index')->name('home');
Route::get('/about-us', 'HomeController@aboutUS')->name('aboutUS');
Route::get('/contact-us', 'HomeController@contactUS')->name('contactUS');
Route::get('/pricing', 'HomeController@pricing')->name('pricing');

 

Step 2: Add Active Class Dynamically

Now, we'll add an active class dynamically based on the URL.

<ul>
    <li class="{{ request()->is('home*') ? 'active' : '' }}">
        <a href="{{ route('home') }}">Home</a>
    </li>
    <li class="{{ request()->is('about-us') ? 'active' : '' }}">
        <a href="{{ route('aboutUS') }}">About US</a>
    </li>
    <li class="{{ request()->is('contact-us') ? 'active' : '' }}">
        <a href="{{ route('contactUS') }}">Contact US</a>
    </li>
    <li class="{{ request()->is('pricing') ? 'active' : '' }}">
        <a href="{{ route('pricing') }}">Pricing</a>
    </li>
</ul>

 

Step 3: Add Active Class CSS

Now, add CSS for the active class.

.active {
    background-color: #ddd;
    color: #fff;
}

 


You might also like:

Recommended Post
Featured Post
How To Get Current Date And Time In Node.js
How To Get Current Date And Ti...

In this example we will see how to get current date and time in Node.js application. In Node.js date and time are handle...

Read More

Sep-01-2021

Laravel 9 CRUD Operation Example
Laravel 9 CRUD Operation Examp...

As we know Laravel 9 was officially released yesterday with many new functionalities like Symfony 6.0 components, Symfon...

Read More

Feb-10-2022

How To Create Zip File In Laravel 7/8
How To Create Zip File In Lara...

In this tutorial I will give you example of how to create zip file in laravel 7/8. Some times client's have requirme...

Read More

Dec-17-2021

Call To Undefined Function mb_strcut() In Laravel
Call To Undefined Function mb_...

Laravel is a fantastic language for web development, but it can throw you a curveball every now and then. If you've...

Read More

Jan-09-2023