php - 如何在 laravel 中检查用户角色并显示选择选项
问题描述
我有不同角色的用户,如管理员、员工、秘书等。
我有一个发送信件的页面,在这个页面中我有一个select option
显示指标。
我希望当具有秘书角色的用户打开此页面时,看到所有指标,但其他角色的其他用户只看到一个指标,如内部信件,我该怎么做?
role
我在和之间有关系user
:
用户模型
public function roles()
{
return $this->belongsToMany(Role::class);
}
好榜样
public function users()
{
return $this->belongsToMany(User::class);
}
这是select option
在发信页面:
<select class="col-12 border mt-2 pt-2" name="indicator_id">
@foreach($indicators as $indicator)
<option value="{{ $indicator->id }}">{{ $indicator->name }}</option>
@endforeach
</select>
如您所见,指标来自其他地方。
这是显示发送信件页面的信件控制器:
$indicators = Indicator::all();
return view('Letter.add', compact('indicators'));
解决方案
将此函数添加到您的用户模型中,以检查用户角色:
/**
* Check if this user belongs to a role
*
* @return bool
*/
public function hasRole($role_name)
{
foreach ($this->roles as $role){
//I assumed the column which holds the role name is called role_name
if ($role->role_name == $role_name)
return true;
}
return false;
}
现在在您看来,您这样称呼它:
<select class="col-12 border mt-2 pt-2" name="indicator_id">
@foreach($indicators as $indicator)
@if (Auth::user()->hasRole('Secretary'))
<option value="{{ $indicator->id }}">{{ $indicator->name }}</option>
@elseif (!Auth::user()->hasRole('Secretary') && {{ $indicator->name }} == 'internalLetter')
<option value="{{ $indicator->id }}">Internal Letter</option>
@endif
@endforeach
</select>
推荐阅读
- wordpress - WP-CLI 导出返回导出项目不需要的一堆作者
- python - 定义和初始化涉及 Asyncio 例程的 python 类的正确/最佳方法是什么
- php - PHP + Twilio + NGROK
- ios - FileManager .removeItem(at:) 需要很长时间——我怎么知道它什么时候完成?
- python - Magicmirror 为 python 创建模块
- java - 线程如何与 Android 中的 Handler 一起工作?
- javascript - 在 Javascript 中自动隐藏其他 div
- reactjs - 如何将 React 钩子表单与 NumberFormat(react-number-format)集成?
- mysql - 自己处理json的mySql函数?
- unity3d - 降低装饰游戏对象的性能成本