Add Classes to Active Link in Laravel
Generally speaking, the easiest way to do this is comparing the name of the current route and the one you’d like to test against.
Luckily, Laravel’s Illuminate\Support\Facades\Route class provides a nice currentRouteName() method that we can use to make a comparison.
Let’s create a little function that you can re-use throughout your application.
This function is great, but it doesn’t do anything with classes. Let’s add a second parameter so that a class string such as ‘bg-gray-900’ could be passed through.
Perfect! Now we can pass in the name of a route and a class string and it will echo the class if the current route matches the one provided.
If we wanted to, we could also wrap this into a custom Blade directive. In any ServiceProvider::boot() , add the following snippet:
Inside of a Blade template, we could now do:
And it would work just the same as calling active_route() directly. Nice!
Going beyond
One way this could be improved is conditionally checking whether or not a second parameter is passed through via the directive. This means you could treat @active as an if statement and do something based on the true and false conditions.
Let’s make the second parameter to active_route() optional and add some checks to see how many parameters the directive receives:
It seems a bit confusing at first, but I’ll break it down:
When our custom directive handler is called, it will receive $expression as a string. For example, @active(‘projects.index’) will mean expression is (‘projects.index’) . The parentheses are included, so we need to remove those from the string before running explode() .
explode(‘,’, . ) will split the string after each , . If two arguments are provided, then were should be a comma separating them. You could run into problems here if you use commas in your route names, but I’ve never seen anybody do that, most people use full-stops. In the case that no commas are present, $parts will just be an array with a single item.
If there is only 1 "part" (the length of $parts is 1), then we can assume that we’re in if else mode, so we return an if statement instead of the string. Luckily, our active_route() function already returns a boolean, no matter the number of arguments received.
Now, we can do something like:
@endactive vs. @endif
We’ve only got a single if statement, so using @endif is perfectly fine. If you wanted to make it a bit prettier, you could just add the following bit of code;
Определение активных ссылок в меню


Почти на всех сайтах необходимо, чтобы пользователь видел, где он сейчас находится. Один из наиболее популярных способов сделать это визуально — подсветить ссылку в меню. Это основы UX:
Проблема не в том, чтобы в ссылку поставить класс «active», а в том, как определить, соответствует ли маршрут ссылке. Не волнуйтесь, Ларавел наколдовал нам немного магии.
Определение маршрута или паттерн адреса
Один из крутых хелперов в фреймворке называется is(). Этот метод доступен для Request и Route и позволяет сравнивать строку с адресом или именем, соответственно. Наш Пользователь может зайти в список подкастов, показывающий последние опубликованные подкасты. Если так и есть, то мы вставляем класса «active» в ссылку, который подсвечивает кнопку.
Код кнопки следующий:
Теперь, когда у нас есть кнопка, нам нужно внедрить класс, если этот маршрут — podcasts или что-то включительно с подстановочным знаком * (wildcard). Мы можем просто использовать метод request()->is() и проверить тот ли это маршрут, что мы ожидаем.
Но есть и другой вариант: проверить название маршрута. Если мы называли наши маршруты соответственно, то мы можем также использовать хелпер маршрутов, чтобы проверить является ли текущий маршрут podcasts и включительно, или нет. Синтаксис такой же, как в исходном коде.
Вот и всё! Не нужно скачивать пакеты или писать полотна кода. Конечно, это компромисс, если вы работаете с несколькими ссылками, но всегда можно автоматически сгенерировать весь список в цикле, чем создавать каждую ссылку вручную.
И, говоря об упрощении жизни, вы можете создать свою собственную команду Blade для автоматической обработки этого кода:
И пока вы это делаете, проверяйте активный маршрут или адрес всего один раз, вместо того, чтобы сравнивать каждый элемент списка, это будет слишком затратно — просто представьте себе сравнение маршрута podcasts/* 100 раз в каждом запросе, безумие!
How to add active class to menu item in laravel
In this session, we will try our hand at solving the «How to add active class to menu item in laravel».
Add active class to menu on visit a specific url
If you want to add active class to the menu item in laravel on visit a specific url then you can use this code snippet in your blade file. This code snippet checks if the visited url is equal to the passed url to the \Request::is() method then it adds the active class to it.
Add active class to menu item on starting url with wildcard url segments
This code snippet add the active class to menu item which have the starting url article/ which we want and the rest will be wildcard url segments, like article/how-to-add-number , article/javascript-element-selector. It will add a class active to the article tab if you visit the first url or the second url in you web browser.
Add active class on matching url segment
You can add an active class to the menu item on matching the url segment. \Request::segment(1) is the method which returns the value passed in the url basic on 0,1,2, . and matches the value we assign after the (==) conditional operator. If the value matches then it adds the class active to the menu item.
Add active class on matching route by name
This code snippet helps you to add an active class using route name in your view file. This is the most recommended way to add active class to menu item because sometimes we need to change the url and after the change of url we don’t have to do anything in the view file.
It will add active class to a menu item on visit all urls assigned to our resourceful controller, like /admin/posts, /admin/posts/create, /admin/posts/1/edit.
Add active class to menu using helper method
You can add an active class to the menu item using the helpers method which is defined in your helpers.php file. After the function definition you have to add this file path in your composer.json file and generate the autoload files using composer dump-autoload command.
After composer dump-autolaod command the helpers autoload file will be generated. You can use helpers method set_active() in your view file.
If you like what you are reading, please consider buying us a coffee ( or 2 ) as a token of appreciation.
Don’t forget to share this article! Help us spread the word by clicking the share button below.
We appreciate your support and are committed to providing you valuable and informative content.
Laravel 9 Link Active Class Routes Example

In this section we will see how to use link active class routes in laravel 9. We will see active link routes in laravel with tailwind css and bootstrap 5.
Example 1
Laravel 9 simple active class link using request()->is(‘/’) and ternary operator.
laravel 9 with tailwind css navbar active links
Example 2
Using routeIs to create active current routes links.
Example 3
You can also use laravel @class directive to active link class with tailwind css navbar links.