Dieser Ansatz ist besonders nützlich, wenn Sie wiederverwendbare Komponenten erstellen, die ihr Verhalten anhand der aktuellen Route anpassen müssen, und redundante bedingte Überprüfungen während Ihrer Anwendung zu vermeiden.
Ein einfaches Beispiel, das diese Methode für die Routenbasis verwendete:
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') ] ] ]); } }
<nav> @foreach($sections as $section) <a href="https://www.php.cn/link/b4930ad58efbbde24d596a387e89adf9'route'%5D)%20%7D%7D" class="{{ $section['active'] ? 'active' : '' }}"> {{ $section['label'] }} </a> @endforeach </nav>
Das obige ist der detaillierte Inhalt vonIntelligente Routenerkennung in Laravel. Für weitere Informationen folgen Sie bitte anderen verwandten Artikeln auf der PHP chinesischen Website!