PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Saturday, February 19, 2022

[FIXED] Setting active class for menu items dynamically in laravel

 February 19, 2022     bootstrap-4, laravel, laravel-5, navigation, php     No comments   

Issue

I'm creating a laravel application using bootstrap 4.

I have my main navigation menu in app.blade.php . And I have four main blades, About,Product,Contact and Blog.

Then I needed to change the menu item active class according to the current page. As the menu being loaded dynamically from the app.blade.php I had to set the active class for current page in the navigation menu dynamically.

What I did was in every blade I've defined a variable called, $currentpage and assign page name in to it, assume it's blog.blade.php

<?php $currentPage = 'blog';?>
@extends('layouts.app')

@section('content')

and in the app.blade.php,

<li class="<?php if($currentPage =='blog'){echo 'nav-item active';}?>">
                            <a class="nav-link " href="{{ url('/blog') }}">{{ __('sentence.Blog') }}</a>
                        </li>

So this works properly..

but I want to know Is this the correct way of doing it and what are the other possible ways to fulfill my requirement


Solution

Instead of defining a $currentPage variable in the layout files, you could use the
request()->is() method:

<li class="nav-item {{ request()->is('blog') ? 'active' : ''}}">
    <a class="nav-link " href="{{ url('blog') }}">{{ __('sentence.Blog') }}</a>
</li>

The is() method essentially takes the current url path for the request and uses Str::is() to check against the pattern you've passed in.

This way you only having to check if the current URL matches the link URL and you don't have to define an extra piece of data somewhere else in your application.



Answered By - Rwd
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing