本文介绍了如何在 laravel 刀片视图中检查用户是否为管理员的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有
用户表如
+================+|用户 |+================+|身份证 |+--------------+|名字 |+--------------+|姓氏 |+--------------+|电子邮件 |+--------------+|密码 |+--------------+和我的角色表
+================+|角色 |+================+|身份证 |+--------------+|姓名 |+--------------+而我的 role_user 表是
+==============+|角色用户 |+==============+|用户 ID |+------------+|role_id |+------------+如何查看当前登录的用户是管理员还是普通用户?
解决方案
Role.php
使用 IlluminateDatabaseEloquentModel;类角色扩展模型{受保护的 $fillable = ['名称'];/*** 一个角色可以有多个用户.** @return IlluminateDatabaseEloquentRelationsBelongsToMany*/公共功能用户(){返回 $this->belongsToMany('AppUser');}}
然后您可以将其添加到用户模型:
公共函数 isAdmin(){foreach ($this->roles()->get() as $role){if ($role->name == 'Admin'){返回真;}}}
查看
@if(Auth::check())@if (Auth::user()->isAdmin())<h2>管理员用户在此处输入代码<h2>@万一@万一
I have
User table like
+==============+ | User | +==============+ | id | +--------------+ | firstname | +--------------+ | lastname | +--------------+ | email | +--------------+ | password | +--------------+
and my roles table
+==============+ | Roles | +==============+ | id | +--------------+ | name | +--------------+
and my role_user table is
+=============+ | role_user | +=============+ | user_id | +-------------+ | role_id | +-------------+
How can I check current logged user is admin or normal user?
解决方案
Role.php
use IlluminateDatabaseEloquentModel;
class Role extends Model {
protected $fillable = [
'name'
];
/**
* A role can have many users.
*
* @return IlluminateDatabaseEloquentRelationsBelongsToMany
*/
public function users() {
return $this->belongsToMany('AppUser');
}
}
Then you can add this to User model:
public function isAdmin()
{
foreach ($this->roles()->get() as $role)
{
if ($role->name == 'Admin')
{
return true;
}
}
}
View
@if(Auth::check())
@if (Auth::user()->isAdmin())
<h2>Admin user enter code here<h2>
@endif
@endif
这篇关于如何在 laravel 刀片视图中检查用户是否为管理员的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!