提供了一個乾淨的解決方案,用於確定當前請求是否與特定路線相匹配。此功能強大的功能可以基於活動路線的有條件邏輯,非常適合分析跟踪,動態導航突出顯示或訪問控制等任務。
在建立需要根據當前路線來調整其行為的可重複使用的組件時,這種方法特別有用,避免了整個應用程序的冗餘條件檢查。
if ($request->route()->named('dashboard')) { // Current route is the dashboard }
該導航組件(集成到您的應用程序中)會自動檢測當前路由並相應地更新導航:
<?php namespace App\View\Components; use Illuminate\View\Component; use Illuminate\Http\Request; class NavigationMenu extends Component { public function __construct(private Request $request) { } public function isActive(string $routeName): bool { return $this->request->route()->named($routeName); } public function isActiveSection(string $section): bool { return $this->request->route()->named("$section.*"); } public function render() { return view('components.navigation-menu', [ 'sections' => [ 'dashboard' => [ 'label' => 'Dashboard', 'route' => 'dashboard', 'active' => $this->isActive('dashboard') ], 'posts' => [ 'label' => 'Blog Posts', 'route' => 'posts.index', 'active' => $this->isActiveSection('posts') ], 'settings' => [ 'label' => 'Settings', 'route' => 'settings.index', 'active' => $this->isActiveSection('settings') ] ] ]); } }
以上是Laravel的智能路線檢測的詳細內容。更多資訊請關注PHP中文網其他相關文章!