如何使用 Auth::user()->id 从其他 table 获取数据
How to get data from other table with Auth::user()->id
我有两个表:Role
和 User
用户
id
name
email
password
Roleid
角色
id
name
我想要的是获取当前登录 User
的 Role
的名称。像 Auth::user()->role()->name;
根据你定义的角色和用户之间的正确关系table你应该这样做:
$user = auth()->user();
$role = $user->role->name // Name of relation function in user model and gather all role data
如果您没有定义用户和角色之间的正确关系,您必须这样做:
在用户 table 中定义一个名为的列:role_id
并在用户模型中执行:
public function role() {
return $this->belongsTo(Role::class, 'role_id');
}
并在角色模型中:
public function users() {
return $this->HasMany(User::class);
}
这是用户模型
/**
* The attributes that are mass assignable.
*
* @var array
*/
protected $fillable = [
'username','name', 'email', 'password','loc_id','role_id','status'
];
/**
* The attributes that should be hidden for arrays.
*
* @var array
*/
protected $hidden = [
'password', 'remember_token',
];
public function role() {
return $this->belongsTo('App\role', 'role_id');
}
}
这是榜样
protected $table="role";
protected $fillable=['rolename',];
public function user() {
return $this->HasMany('App\User');
}
这两个table是一对多的关系。每个用户都有一个 roleid 通过使用这个角色 id 想通过使用 roleid(forgein key) 从角色 table 中获取当前登录用户 rolename 的名称
{{Auth::user()->role()->rolename}}
我正在使用它来获取角色名称但出现错误。
未定义 属性: Illuminate\Database\Eloquent\Relations\BelongsTo::$rolename
如果您只想使用用户 ID,请使用此最佳方式。
$user_id = Auth::id();
否则需要特定值,
$user_email = Auth::user()->email;
请这样写:
{{Auth::user()->role->rolename}}
不要添加 ()
角色
我有两个表:Role
和 User
用户
id
name
email
password
Roleid
角色
id
name
我想要的是获取当前登录 User
的 Role
的名称。像 Auth::user()->role()->name;
根据你定义的角色和用户之间的正确关系table你应该这样做:
$user = auth()->user();
$role = $user->role->name // Name of relation function in user model and gather all role data
如果您没有定义用户和角色之间的正确关系,您必须这样做:
在用户 table 中定义一个名为的列:role_id
并在用户模型中执行:
public function role() {
return $this->belongsTo(Role::class, 'role_id');
}
并在角色模型中:
public function users() {
return $this->HasMany(User::class);
}
这是用户模型
/**
* The attributes that are mass assignable.
*
* @var array
*/
protected $fillable = [
'username','name', 'email', 'password','loc_id','role_id','status'
];
/**
* The attributes that should be hidden for arrays.
*
* @var array
*/
protected $hidden = [
'password', 'remember_token',
];
public function role() {
return $this->belongsTo('App\role', 'role_id');
}
}
这是榜样
protected $table="role";
protected $fillable=['rolename',];
public function user() {
return $this->HasMany('App\User');
}
这两个table是一对多的关系。每个用户都有一个 roleid 通过使用这个角色 id 想通过使用 roleid(forgein key) 从角色 table 中获取当前登录用户 rolename 的名称 {{Auth::user()->role()->rolename}} 我正在使用它来获取角色名称但出现错误。
未定义 属性: Illuminate\Database\Eloquent\Relations\BelongsTo::$rolename
如果您只想使用用户 ID,请使用此最佳方式。
$user_id = Auth::id();
否则需要特定值,
$user_email = Auth::user()->email;
请这样写:
{{Auth::user()->role->rolename}}
不要添加 ()
角色