Laravel8 基于自定义中间件实现不同账户类型仪表盘访问限制
实现方案
以下实现完全基于Laravel原生功能,无需引入任何第三方包:
步骤1:生成并编写中间件
执行Artisan命令生成中间件:
php artisan make:middleware CheckAccountType
打开生成的app/Http/Middleware/CheckAccountType.php文件,替换内容为:
<?php namespace App\Http\Middleware; use Closure; use Illuminate\Http\Request; class CheckAccountType { public function handle(Request $request, Closure $next, string $requiredAccountType) { // 前置已通过auth中间件,可直接获取登录用户信息 if (auth()->user()->account_type !== $requiredAccountType) { // 账号类型不匹配时跳转到对应用户自己的仪表盘,也可直接返回403错误:abort(403) return auth()->user()->account_type === 'profile' ? redirect()->route('dashboard_profile')->with('error', '你无权访问企业端页面') : redirect()->route('dashboard_business')->with('error', '你无权访问个人端页面'); } return $next($request); } }
步骤2:注册中间件
打开app/Http/Kernel.php文件,找到$routeMiddleware数组,添加如下条目:
protected $routeMiddleware = [ // 原有其他中间件保持不变 'account_type' => \App\Http\Middleware\CheckAccountType::class, ];
步骤3:绑定中间件到对应页面
有两种绑定方式二选一即可:
方式A:在控制器中绑定(推荐,和你现有写法一致)
修改BusinessDashboardController.php的构造方法:
public function __construct() { $this->middleware('auth'); $this->middleware('account_type:business'); }
修改ProfileDashboardController.php的构造方法:
public function __construct() { $this->middleware('auth'); $this->middleware('account_type:profile'); }
方式B:在路由文件中绑定
打开routes/web.php,给对应路由附加中间件即可:
use App\Http\Controllers\Auth\BusinessDashboardController; use App\Http\Controllers\Auth\ProfileDashboardController; Route::get('/dashboard/business', [BusinessDashboardController::class, 'index']) ->middleware(['auth', 'account_type:business']) ->name('dashboard_business'); Route::get('/dashboard/profile', [ProfileDashboardController::class, 'index']) ->middleware(['auth', 'account_type:profile']) ->name('dashboard_profile');
完成以上步骤后,个人用户访问企业仪表盘、企业用户访问个人仪表盘时都会被自动拦截跳转,页面访问权限即可得到保护。
内容的提问来源于stack exchange,提问作者Ginz77
相关产品推荐
相关产品推荐

