如果我的用户是管理员,我有一个问题如何检查刀片。 我创建了3个表:users,roles和users_roles。 这就是我的代码的样子:
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");
} }
现在我想检查刀片是用户admin,acctualy if 用户表中的roleName =' admin'?但我不知道该怎么做。 提前感谢您的帮助
答案 0 :(得分:1)
有很多方法可以进行此检查。这是其中之一
将其添加到User
模型
public function isAdmin()
{
return !! $this->roles()->where('roleName', 'admin')->count();
}
然后您可以在用户上调用isAdmin
方法。
$user = User::find(1);
if ($user->isAdmin()) {
// user is admin
}
答案 1 :(得分:0)
// 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
@if(Auth::User()->inRole('admin') == 1) {
//admin
}
@elseif(Auth::User()->inRole('manager') == 1) {
//managaer
}
@else {
//user
}