用户型号:
class User extends Authenticatable
{
use Notifiable;
protected $table = 'users';
/**
* The attributes that are mass assignable.
*
* @var array
*/
protected $fillable = [
'name', 'email', 'password',
];
/**
* The attributes that should be hidden for arrays.
*
* @var array
*/
protected $hidden = [
'password', 'remember_token', 'role_id',
];
protected $appends = [
'role',
];
public function getRoleAttribute()
{
return $this->role->name;
}
/**
* User role.
*
* @return \Illuminate\Database\Eloquent\Relations\BelongsTo
*/
public function role()
{
return $this->belongsTo('App\Role');
}
}
我不想显示角色的名称,而是显示角色 ID。
但它说:
User.php 第 38 行中的 ErrorException:未定义属性:App\User::$role
角色表包含一个id和name
users 表包含一个role_id
编辑:
当我尝试return $this->role()->name;
时,它给了我一个:
User.php 第 38 行中的 ErrorException:未定义属性:Illuminate\Database\Eloquent\Relations\BelongsTo::$name
但是我检查角色并且有效...
/**
* Check if the user is an admin.
*
* @return bool
*/
public function isAdmin()
{
if ($this->role->name == 'admin') {
return true;
}
return false;
}