首页 > 解决方案 > 如何在 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'));

标签: phplaravellaravel-5laravel-7

解决方案


将此函数添加到您的用户模型中,以检查用户角色:

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

推荐阅读