Pendekatan ini amat berguna apabila membina komponen yang boleh diguna semula yang perlu menyesuaikan tingkah laku mereka berdasarkan laluan semasa, mengelakkan pemeriksaan bersyarat yang berlebihan di seluruh aplikasi anda.
Contoh mudah menggunakan kaedah ini untuk logik berasaskan laluan:
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>
Atas ialah kandungan terperinci Pengesanan laluan pintar di Laravel. Untuk maklumat lanjut, sila ikut artikel berkaitan lain di laman web China PHP!