How to Add Active Class Dynamically in Laravel?

By Hardik Savani November 5, 2023 Category : Laravel

Hi Artisan,

I am going to explain to you example of how to add active class dynamically in laravel. I’m going to show you about how to add active class dynamically in laravel 10. This article will give you a simple example of laravel add active class to menu. you'll learn laravel add active class request is() method. So, let us dive into the details.

In Laravel, you can add an active class to elements dynamically, such as menu items or links, based on the current route or page being visited. This helps you highlight the active link or menu item in your navigation, making it easier for users to understand their current location within your website.

Here's an example of how you can add an active class to a menu item dynamically in Laravel using Blade templates and the `request()` function:

Step 1: Add Routes

First, make sure you have a route set up in your `web.php` file (or routes file) using the `route` helper:

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

Create a Blade view that contains your navigation menu, for example, `layouts/app.blade.php`:



<li class="{{ request()->is('home*') ? 'active' : '' }}">

<a href="{{ route('home') }}">Home</a>


<li class="{{ request()->is('about-us') ? 'active' : '' }}">

<a href="{{ route('aboutUS') }}">About US</a>


<li class="{{ request()->is('contact-us') ? 'active' : '' }}">

<a href="{{ route('contactUS') }}">Contact US</a>


<li class="{{ request()->is('pricing') ? 'active' : '' }}">

<a href="{{ route('pricing') }}">Pricing</a>




In this example, we're using the `request()->is('pattern')` function to check if the current URL matches a specific pattern. If the pattern matches, the 'active' class is added to the `

  • ` element.

    Step 3: Add Active Class CSS

    Define your 'active' class in your CSS. For example, in your CSS file (e.g., `styles.css`), you can have:

    .active {

    background-color: #3498db;

    color: #fff;

    /* Add any styles you want for the active menu item */


    Make sure to link your CSS file to your Blade template.

    Now, when you visit the "home" route, the "Home" menu item will have the 'active' class, and the CSS styles specified in your CSS file will be applied.

    Repeat the same process for other menu items or links in your navigation menu. The `request()->is('pattern')` function allows you to match patterns to determine which menu items should be marked as active.

    Remember to adjust the route names and URL patterns to match your application's routes and structure.

    I hope it can help you...

  • Tags :