如何检查用户角色并在 laravel 中显示 select 选项

How to check user role and show select option in laravel

我有不同角色的用户,如管理员、员工、秘书等

我有一个发送信件的页面,在这个页面我有一个 select option 来显示指标。

我希望当具有秘书角色的用户打开此页面时,看到所有指示器,但具有其他角色的其他用户只能看到一个指示器,如内部信件,我该怎么做?

我在 roleuser 之间有关系:

用户模型

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'));

将此函数添加到检查用户角色的 User 模型:

   /**
 * 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>