如何在使用用户与管理员双中间件时让Blade模板对两者均可见?
First, let's confirm you've got your authentication guards set up correctly in config/auth.php (this is foundational for the rest to work):
'guards' => [ 'web' => [ 'driver' => 'session', 'provider' => 'users', ], 'admin' => [ 'driver' => 'session', 'provider' => 'admins', ], ], 'providers' => [ 'users' => [ 'driver' => 'eloquent', 'model' => App\Models\User::class, ], 'admins' => [ 'driver' => 'eloquent', 'model' => App\Models\Admin::class, ], ],
Option 1: Custom Middleware (Recommended for Reusability)
If you need this access logic across multiple controllers, creating a dedicated middleware is the cleanest, most maintainable approach:
Generate the middleware
Run this Artisan command in your terminal:php artisan make:middleware AllowUserOrAdminUpdate the middleware logic
Openapp/Http/Middleware/AllowUserOrAdmin.phpand replace thehandlemethod with this:public function handle($request, Closure $next) { // Check if either a regular user or admin is authenticated if (auth('web')->check() || auth('admin')->check()) { return $next($request); } // Redirect unauthenticated users to your preferred login page return redirect()->route('login'); }Register the middleware
Add this entry to the$routeMiddlewarearray inapp/Http/Kernel.php:'allow.user.or.admin' => \App\Http\Middleware\AllowUserOrAdmin::class,Use the middleware in your controller
Replace your existing middleware call in the controller constructor:public function __construct() { $this->middleware('allow.user.or.admin'); }
Option 2: Closure Middleware (Quick One-Off Solution)
If you only need this access rule for a single controller, you can use an inline closure instead of creating a separate middleware file:
public function __construct() { $this->middleware(function ($request, $next) { // Allow access if either guard has an authenticated user if (auth('web')->check() || auth('admin')->check()) { return $next($request); } return redirect()->route('login'); }); }
Bonus: Differentiate Content in Blade (If Needed)
If you want to show specific content to regular users vs admins while keeping the template accessible to both, add this to your Blade file:
@if(auth('web')->check()) <div class="user-greeting">Welcome, regular user!</div> @elseif(auth('admin')->check()) <div class="admin-greeting">Welcome, admin! Here's your dashboard shortcut</div> @endif
Key Notes
- Make sure your login routes for both guards are properly set up (e.g.,
admin/loginwith a named route likeadmin.loginif you want to redirect unauthenticated admins to their own login page). - Use
auth('guard-name')->user()if you need to access the authenticated user's details in your controller or Blade template.
内容的提问来源于stack exchange,提问作者Mosharof Hossain

