How to Add Active Class Dynamically in Laravel

  Oct 2023
  ITSolutionsGuides
  Category: Laravel
How to Add Active Class Dynamically in Laravel

Hi Developers,

Lets see How to Add Active Class Dynamically in Laravel, In this tutorial we see the most common way to Add active class dynamically in laravel. It is a quick and simple way to solve it. While creating the websites using laravel we basically use same layout blade file for all the pages, So its tricky to add separate active class for the navbar to overcome this we will follow the most common and simple solution to achieve this. Simply while returning the blade file in the controller function we will also add a new variable and call the view along with the variable using the compact() function. Then in the blade file depending on the data in the variable we will determine which one should be active by using @if ... @endif so lets see How to Add Active Class Dynamically in Laravel.

Elevate your Laravel web development with our tutorial on dynamically adding active classes. Learn to create responsive navigation that dynamically highlights the active route, enhancing user experience and navigation intuitiveness in your applications.

Let's Start Coding

In the Controller File,

We are sending the variable data in the name of active using compact()

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;

class UserController extends Controller
{
  
    public function index()
    {        
        $active = "index";               
        return view('index')->with(compact('active'));
    }
}

Let's Start Coding

In the Blade File,

We are using the blade directives @if .... @endif inside the class attribute of the li tag to check the data in the variable $active

<ul>
    <li class="@if ($active == 'index') active @endif">
        <a href="{{ route('index') }}">Home</a>
    </li>
   <li class="@if ($active == 'about') active @endif">
        <a href="{{ route('about') }}">About</a>
    </li>   
</ul>

We hope it helps everyone. Thanks for supporting ITSolutionsGuides and keep supporting us also follow us in social media platforms.

Subscribe for NewsLetter

Be the first to know about releases and tutorial news and solutions.

We care about your data in our privacy policy.

ITSolutionsGuides

ITSolutionsGuides was started mainly to provide good and quality web solutions for all the developers. We provide tutorials to support all the developers and also we try to provide solutions to the errors we face while coding.

Contact US

ITSolutionsGuides, provide users with an easy-to-use form to reach out for support or inquiries.

whatsapp  gmail  instagram-new--v1  facebook-circled  twitter-circled  linkedin  github  pinterest 

Copyright © 2023 - 2024 All rights reserved | ITSolutionsGuides