Pau*_*ero 22 php laravel laravel-5.4
现在我已经按照Laravel文档介绍了如何在身份验证期间允许用户名,但它会丢失使用电子邮件的能力.我想允许用户使用他们的用户名或电子邮件登录.我该怎么做?
我已根据Laravel的文档将此代码添加到LoginController,它只允许用户名登录.我希望它接受用户名或电子邮件登录.
public function username () {
return 'username';
}
Run Code Online (Sandbox Code Playgroud)
小智 52
我认为更简单的方法是覆盖LoginController中的username方法:
public function username()
{
$login = request()->input('login');
$field = filter_var($login, FILTER_VALIDATE_EMAIL) ? 'email' : 'username';
request()->merge([$field => $login]);
return $field;
}
Run Code Online (Sandbox Code Playgroud)
Edd*_*ove 21
请按照以下链接中的说明操作:https://laravel.com/docs/5.4/authentication#authenticating-users
然后你可以检查这样的用户输入
$username = $request->username; //the input field has name='username' in form
if(filter_var($username, FILTER_VALIDATE_EMAIL)) {
//user sent their email
Auth::attempt(['email' => $username, 'password' => $password]);
} else {
//they sent their username instead
Auth::attempt(['username' => $username, 'password' => $password]);
}
//was any of those correct ?
if ( Auth::check() ) {
//send them where they are going
return redirect()->intended('dashboard');
}
//Nope, something wrong during authentication
return redirect()->back()->withErrors([
'credentials' => 'Please, check your credentials'
]);
Run Code Online (Sandbox Code Playgroud)
这只是一个样本.你可以采取无数种方法来实现同样的目标.
小智 7
打开LoginController.php文件。
添加此参考
use Illuminate\Http\Request;
Run Code Online (Sandbox Code Playgroud)并覆盖凭据方法
protected function credentials(Request $request)
{
$field = filter_var($request->get($this->username()), FILTER_VALIDATE_EMAIL)
? 'email'
: 'username';
return [
$field => $request->get($this->username()),
'password' => $request->password,
];
}
Run Code Online (Sandbox Code Playgroud)在Laravel 5.7.11中成功测试
| 归档时间: |
|
| 查看次数: |
24567 次 |
| 最近记录: |