I thought to write static routes like contact, imprint or "About Us" in the web.php as a one-liner. I saw this at Laravel Daily.
web.php
Route::get('/{page}', App\Http\Controllers\StaticPageController::class)
->name('page')
->where('page', 'about-us|imprint|contact');
It's nice but I'm getting problems with my navbar.
My Blade navbar has a dynamic part. The current menu item is highlighted. Very simple.
nav.blade.php
<x-nav-link :href="route('about-us')" :active="request()->routeIs('about-us')">
{{ __('About us') }}
</x-nav-link>
With the new one-liner, I then get the following error message:
Symfony\Component\Routing\Exception\RouteNotFoundException.
Route [about-us] not defined. (View: /project01/resources/views/includes/nav.blade.php)
Which is logical, because I no longer have the about-us route.
Actually, the route should be given a corresponding array mapping. But I don't know how. How can I solve the problem?
The solution for this problem will be:
<x-nav-link :href="route('page', ['page' => 'about-us'])" :active="request()->routeIs('about-us')">
{{ __('About us') }}
</x-nav-link>
Special Thanks for all good answears!
My Answer:
You're on the right track with your solution! By using the route() helper function with the 'page' route name and passing in the page parameter as an array, you can dynamically generate the route for the static pages.
Here's the updated code for your nav.blade.php file:
php
{{ __('About us') }}
This way, you are telling Laravel to generate the route for the 'page' route name and passing in the 'about-us' parameter as the page value. This will dynamically generate the correct route for the 'about-us' static page.
You can apply the same logic for the other static pages in your navbar as well. Just make sure to pass in the correct page parameter for each link.
I hope this helps! Let me know if you have any other questions.
Rate this post
3 of 5 based on 9001 votesComments