Welcome to WuJiGu Developer Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
429 views
in Technique[技术] by (71.8m points)

How to mark a parent menu as active if any of it's child is active using Laravel and Eloquent?

I want to create a list of menu for my dashboard. It consists of menu name and url. Each item acts like this:

  • Menu 1 <-- this menu is active because it's child (Menu 1.1) is selected
    • Menu 1.1 <-- this menu is selected
    • Menu 1.2
      • Menu 1.2.1
    • Menu 1.3
  • Menu 2
  • Menu 3

And like this, too:

  • Menu 1 <-- this menu is active because it's child (Menu 1.2) is active
    • Menu 1.1
    • Menu 1.2 <-- this menu is active because it's child (Menu 1.2.1) is selected
      • Menu 1.2.1 <-- this menu is selected
    • Menu 1.3
  • Menu 2
  • Menu 3

I want to achieve this using Laravel 8 and Eloquent. Any help is appreciated.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Assuming you are in a blade file, you can leverage the routeIs() method from the request() helper.
The routeIs() method can take one or multiple pattern to check so for example, lets say you have 2 routes:

  1. user
  2. user.role

so now we are on the user.role route and in our blade file we are making the following check

 request()->routeIs('user') //false
 request()->routeIs('user.role') //true
 request()->routeIs('user','user.role') //true - since the second is valid
 request()->routeIs('user.*') //true - wildcard is accepted

Doc reference to the helper https://laravel.com/docs/8.x/requests#inspecting-the-request-path

I hope it can give you the tool to build your menu and the Active state


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to WuJiGu Developer Q&A Community for programmer and developer-Open, Learning and Share

2.1m questions

2.1m answers

62 comments

56.6k users

...