You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Laravel中如何按用户角色控制发送信件页的指标下拉选项

解决方案:根据用户角色动态显示指标下拉选项

1. 在User模型中添加角色判断方法

先给User模型加一个便捷方法,用来快速判断当前用户是否是Secretary角色:

// app/Models/User.php
public function isSecretary()
{
    // 这里假设你的Role表中,Secretary角色的name字段值是"Secretary",根据实际情况调整
    return $this->roles()->where('name', 'Secretary')->exists();
}

2. 在控制器中根据角色筛选指标

修改LetterController的add方法,根据当前登录用户的角色来获取对应的指标数据:

// app/Http/Controllers/LetterController.php
use Illuminate\Support\Facades\Auth;
use App\Models\Indicator;

public function add()
{
    $user = Auth::user();
    
    // 区分角色获取指标
    if ($user->isSecretary()) {
        // 秘书角色显示所有指标
        $indicators = Indicator::all();
    } else {
        // 其他角色仅显示"内部信件"指标,根据你的实际指标名称/ID调整查询条件
        $indicators = Indicator::where('name', '内部信件')->get();
        // 如果是用ID筛选更可靠(避免名称变更):
        // $indicators = Indicator::where('id', 1)->get(); // 替换1为你的内部信件指标ID
    }

    return view('Letter.add', compact('indicators'));
}

3. (可选但推荐)后端权限验证

为了防止用户通过修改前端HTML来提交未授权的指标ID,在保存信件的store方法中也要添加权限校验:

public function store(Request $request)
{
    $user = Auth::user();
    
    if (!$user->isSecretary()) {
        // 获取允许的指标ID
        $allowedIndicatorId = Indicator::where('name', '内部信件')->value('id');
        // 校验提交的指标ID是否合法
        if ($request->input('indicator_id') != $allowedIndicatorId) {
            abort(403, '你没有权限选择该指标');
        }
    }

    // 执行后续的信件保存逻辑...
}

补充说明

  • 如果你的Role表使用slug字段(比如secretary)代替name来标识角色,把where('name', 'Secretary')改成where('slug', 'secretary')会更稳定,避免名称大小写或翻译问题。
  • 如果后续需要扩展更多角色和权限,推荐使用成熟的权限管理包,但当前方案已经能满足你的需求。

内容的提问来源于stack exchange,提问作者Pooriya Mostaan

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.07 18:52:50