4

用户型号:

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

角色表包含​​一个idname

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;
} 
4

2 回答 2

7

这是因为您有角色属性和角色关系,尝试重命名其中一个,它将与return $this->role->name;

于 2017-01-30T15:35:10.397 回答
0

使用关系,而不是属性:

{{ $user->role()->name }}
于 2017-01-30T14:06:22.020 回答