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

ロール テーブルにはID名前が含まれています

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