我必须在laravel中构建登录。通常没问题。但我的客户想要使用一些特殊用户名登录。它应该是surname-userId。
所以有用户表:
id; firstname; lastname; email; ...
1; testuser1; Smith; testuser1.smith@anyprovider.xx;
此处的登录名应为“Smith-1”。我刚刚找到了覆盖LoginController中的函数username()的解决方案。但在这种情况下,我需要组合两个表字段来构建用户名。
以前是否有人这样做过?
答案 0 :(得分:1)
只是重载方法attemptLogin
答案 1 :(得分:0)
就像哈萨诺夫所说的那样,重载attemptLogin函数就足够了。 EloquentUserProvider使用给定的凭据构建查询:
/**
* Retrieve a user by the given credentials.
*
* @param array $credentials
* @return \Illuminate\Contracts\Auth\Authenticatable|null
*/
public function retrieveByCredentials(array $credentials)
{
if (empty($credentials)) {
return;
}
// First we will add each credential element to the query as a where clause.
// Then we can execute the query and, if we found a user, return it in a
// Eloquent User "model" that will be utilized by the Guard instances.
$query = $this->createModel()->newQuery();
foreach ($credentials as $key => $value) {
if (! Str::contains($key, 'password')) {
$query->where($key, $value);
}
}
return $query->first();
}
所以我只是将输入的用户名分成两个字段,UserProvider完成剩下的工作:
/**
* Attempt to log the user into the application.
*
* @param \Illuminate\Http\Request $request
* @return bool
*/
protected function attemptLogin(Request $request)
{
$credentials = $this->credentials($request);
list($lastname, $id) = explode('-', $credentials[$this->username()]);
$params = [
'id' => (int) $id,
'name' => $lastname,
'password' => $credentials['password'],
];
return $this->guard()->attempt(
$params, $request->has('remember')
);
}