如何检查用户角色并在 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'));


慕仙森
浏览 88回答 1
1回答

守着一只汪

将此功能添加到检查用户角色的用户模型中:&nbsp; &nbsp;/**&nbsp;* Check if this user belongs to a role&nbsp;*&nbsp;* @return bool&nbsp;*/&nbsp;public function hasRole($role_name)&nbsp;{&nbsp; &nbsp; &nbsp;foreach ($this->roles as $role){&nbsp; &nbsp; &nbsp; &nbsp; &nbsp;//I assumed the column which holds the role name is called role_name&nbsp; &nbsp; &nbsp; &nbsp; &nbsp;if ($role->role_name == $role_name)&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;return true;&nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp;return false;&nbsp;}现在在您看来,您可以这样称呼它:<select class="col-12 border mt-2 pt-2" name="indicator_id">&nbsp; &nbsp; @foreach($indicators as $indicator)&nbsp; &nbsp;&nbsp;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; @if (Auth::user()->hasRole('Secretary'))&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; <option value="{{ $indicator->id }}">{{ $indicator->name }}</option>&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; @elseif (!Auth::user()->hasRole('Secretary') && {{ $indicator->name }} == 'internalLetter')&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;<option value="{{ $indicator->id }}">Internal Letter</option>&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; @endif&nbsp; &nbsp; @endforeach&nbsp; &nbsp;</select>
打开App,查看更多内容
随时随地看视频慕课网APP