Laravel“密码错误"错误信息 [英] Laravel "Wrong password" error message
问题描述
我正在Laravel 5.4中创建一个登录功能,并且当密码不正确时,我想在视图中显示错误消息.另外,我还有一条自定义消息,用于帐户批准,因此这对我来说有点困难.同时,我将这些消息放在一起,但不是非常用户友好.我如何分开它们?
I'm creating a login function in Laravel 5.4 and I want to show error message in the view when the password is incorrect. Also I have a custom message for account approval so it makes things a bit difficult for me. Meanwhile I put those messages together but is not very user-friendly. How can I separate them?
这是我的控制者:
public function login(Request $request)
{
// validate the form data
$this->validate($request, [
'email' => 'required|email|exists:users,email',
'password' => 'required|min:6'
]);
// attempt to log
if (Auth::attempt(['approve' => '1', 'email' => $request->email, 'password' => $request->password ], $request->remember)) {
// if successful -> redirect forward
return redirect()->intended(route('user.overview'));
}
// if unsuccessful -> redirect back
return redirect()->back()->withInput($request->only('email', 'remember'))->withErrors([
'approve' => 'Wrong password or this account not approved yet.',
]);
}
因此,我想用两个单独的消息替换Wrong password or this account not approved yet
:
As result i want to replace Wrong password or this account not approved yet
with two separate messages:
如果密码输入错误:Password is wrong
如果帐户未获批准,请显示:This account not approved yet
If password is wrong to show: Password is wrong
If account not approved show: This account not approved yet
推荐答案
您可以为每个验证规则传递自定义错误消息,您可以这样做:
You can pass custom error messages for each validation rule, you can do this:
public function login(Request $request)
{
//Error messages
$messages = [
"email.required' => "Email is required",
"email.email' => "Email is not valid",
"email.exists' => "Email doesn't exists",
"password.required" => "Password is required",
"password.min" => "Password must be at least 6 characters"
];
// validate the form data
$validator = Validator::make($request->all(), [
'email' => 'required|email|exists:users,email',
'password' => 'required|min:6'
], $messages);
if ($validator->fails()) {
return back()->withErrors($validator)->withInput();
} else {
// attempt to log
if (Auth::attempt(['approve' => '1', 'email' => $request->email, 'password' => $request->password ], $request->remember)) {
// if successful -> redirect forward
return redirect()->intended(route('user.overview'));
}
// if unsuccessful -> redirect back
return redirect()->back()->withInput($request->only('email', 'remember'))->withErrors([
'approve' => 'Wrong password or this account not approved yet.',
]);
}
}
在此之前,您必须包括Validator类:
Before this, you have to include Validator class:
use Illuminate\Support\Facades\Validator;
这篇关于Laravel“密码错误"错误信息的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!