Laravel不同页面调用不同页眉报错及实现方法咨询
Hey there! Let's break down what's going wrong and get your custom headers working for the hosting and about pages.
Why the Error Happens
The Undefined class constant 'hosting' error pops up because you're trying to access a non-existent constant hosting on the Route class. Laravel's Route facade doesn't have predefined constants for your page names—so we need to use the correct methods to check which page the user is on.
Solution 1: Check by Route Name (Recommended)
This is the most robust approach because route URIs might change, but route names usually stay consistent.
Step 1: Name Your Routes
First, make sure your hosting and about routes have names in routes/web.php:
// routes/web.php Route::get('/hosting', [HostingController::class, 'index'])->name('hosting'); Route::get('/about', [AboutController::class, 'index'])->name('about');
Step 2: Conditionally Include Headers in Your View
Replace your broken code with this in your blade file:
@if(Route::currentRouteName() === 'hosting') @include('partials.header') @elseif(Route::currentRouteName() === 'about') @include('partials.header1') @endif
Solution 2: Check by Request URI
If you don't want to name your routes, you can check the current request's URI directly:
@if(request()->path() === 'hosting') @include('partials.header') @elseif(request()->path() === 'about') @include('partials.header1') @endif
Note: If your routes have a prefix (like /admin/hosting), use the full path here (e.g., admin/hosting).
Solution 3: Use View Composers (For Scalable Setups)
If you plan to add more pages with custom headers later, view composers let you centralize the logic instead of repeating it in every view.
Step 1: Add Logic to ViewServiceProvider
Open App\Providers\ViewServiceProvider.php and update the boot method:
// App\Providers\ViewServiceProvider.php use Illuminate\Support\Facades\View; use Illuminate\Support\Facades\Route; public function boot() { View::composer(['hosting', 'about'], function ($view) { $headerPartial = match(Route::currentRouteName()) { 'hosting' => 'partials.header', 'about' => 'partials.header1', default => 'partials.header', // Fallback header if needed }; $view->with('headerPartial', $headerPartial); }); }
Step 2: Include the Header in Your View
Now you can cleanly include the header without conditionals in your blade files:
@include($headerPartial)
Quick Checks to Avoid Issues
- Make sure the partial views
partials.headerandpartials.header1exist inresources/views/partials/(double-check filenames for typos!). - If you're using Laravel versions older than 8.x, adjust the controller syntax in routes (e.g.,
Route::get('/hosting', 'HostingController@index')->name('hosting')).
内容的提问来源于stack exchange,提问作者sharmila

