Php 如何检查我的用户是否是管理员
我有一个问题,如果我的用户是管理员,如何签入刀片服务器。 我创建了3个表:用户、角色和用户/角色。 这就是我的代码的外观:Php 如何检查我的用户是否是管理员,php,laravel,admin,Php,Laravel,Admin,我有一个问题,如果我的用户是管理员,如何签入刀片服务器。 我创建了3个表:用户、角色和用户/角色。 这就是我的代码的外观: Users table: public function up() { Schema::create('users', function (Blueprint $table) { $table->increments('id'); $table->string('name'); $table->string('
Users table:
public function up() {
Schema::create('users', function (Blueprint $table) {
$table->increments('id');
$table->string('name');
$table->string('email')->unique();
$table->string('password');
$table->rememberToken();
$table->timestamps(); }); }
Roles table:
public function up(){
Schema::create('roles', function (Blueprint $table){
$table->increments('id');
$table->string('roleName');
$table->timestamps(); }); }
Users_roles table:
public function up()
{
Schema::create('users_roles', function (Blueprint $table) {
$table->increments('id');
$table->integer('user_id')->unsigned();
$table->foreign('user_id')->references('id')->on('users');
$table->integer('role_id')->unsigned();
$table->foreign('role_id')->references('id')->on('roles');
$table->timestamps(); }); }
And models:
User model:
class User extends Authenticatable {
protected $fillable = [
'name', 'email', 'password', ];
public function roles(){
return $this->belongsToMany("App\Roles", "users_roles");
} }
Roles model:
class Roles extends Model {
public function users(){
return $this->belongsToMany("App\User");
} }
现在我想签入blade是用户管理员,如果
用户表中的角色名称='admin'?但我不知道该怎么做。
提前感谢您的帮助进行此检查的方法很多。这是其中之一 将其添加到用户模型中 然后可以对用户调用isAdmin方法
$user = User::find(1);
if ($user->isAdmin()) {
// user is admin
}
//User.php
class User extends Authenticatable {
protected $fillable = [ 'name', 'email', 'password', ];
public function roles(){
return $this->belongsToMany('App\Roles', 'users_roles','user_id', 'role_id');
}
public function inRole($rol) {
$check = $this->roles()->where('roleName', $rol)->first();
if($check == "") {
return 0;
}
else {
return 1;
}
}
}
//Roles.php
class Roles extends Model {
protected $table = 'roles';
public function users(){
return $this->belongsToMany('App\User', 'users_roles',
'role_id', 'user_id');
}
}
现在,在视图模板中,您可以通过将rolename作为参数传递来检查任何角色
e、 g
类似于$user->whereHas'roles',函数$q{$q->where'roleName',admin';};-阅读雄辩的人际关系@然而,mkaatman关于使用本机授权支持的建议是好的。
class Roles extends Model {
protected $table = 'roles';
public function users(){
return $this->belongsToMany('App\User', 'users_roles',
'role_id', 'user_id');
}
}
@if(Auth::User()->inRole('admin') == 1) {
//admin
}
@elseif(Auth::User()->inRole('manager') == 1) {
//managaer
}
@else {
//user
}