我正在制作一个简单的登录/注册系统,注册部分正在工作,但我在登录部分有一些问题。我正在使用Laravel 9和docker,还有MySQL。我有一个登录控制器:
use AppHttpRequestsLoginRequest;
use IlluminateHttpRequest;
use IlluminateSupportFacadesAuth; //Es una clase para manejar autenticacion
use IlluminateContractsValidationFactory as ValidationFactory;
class LoginController extends Controller
{
public function show(){
return view('login');
}
public function login(LoginRequest $request){
$credentials = $this->getCredentials(); //esto viene de la login request, puede ser el user y la contra o el mail y la contra
if(!Auth::validate($credentials)){
return redirect()->to('/login')->withErrors('Usuario o contraseña incorrectos');
}
$user = Auth::getProvider()->retrieveByCredentials($credentials);
Auth::login($user);
return view('index');
}
public function authenticated(Request $request, $user){
return view('index');
}
LoginRequest.php文件
use IlluminateFoundationHttpFormRequest;
use IlluminateContractsValidationFactory as ValidationFactory;
class LoginRequest extends FormRequest
{
public function authorize()
{
return true;
}
public function rules()
{
return [
'user' => 'required|string|max:32',
'password' => 'required|string|max:16',
];
}
public function getCredentials(){
$user = $this->get('user');
if($this->isEmail($user)){ //Si es un correo electronico la solicitud sera con un email
return [
'email' => $user,
'password' => $this->get('password')
];
}
return $this->only('username', 'password');
}
public function isEmail($value){
$factory = $this->container->make(Validation::class);
return !$factory->make(['user' => $value], ['user' => 'email'])->fails();
}
}
和路由文件Web.php用这两个方法登录:
Route::get('/login', [LoginController::class, 'show']);
Route::post('/login', [LoginController::class, 'login']);
现在,当我把登录按钮在页面中,有良好的凭据,它不会重定向到索引页,它只重新加载登录页面与下一个URL:https://gymreadyweb.ddev.site/login?_token=QrMFA1ug8coZCTXvS80ujEbEfBkR4QINWnfHUKtJ&用户= gaspar&密码= prueba1
如果我用错误的凭据做它也是一样的。我不知道还能做什么。
在我提出建议之前,我想向您推荐……请保持你的代码干净,并尽量遵循DRY和SOLID范例。
我还想建议不要重新发明轮子。
我认为你的实现可以这样简化:
use IlluminateHttpRequest;
use IlluminateSupportFacadesAuth;
class LoginController extends Controller
{
/** TODO: Document this... */
public function show()
{
return view('login');
}
/** TODO: Document this... */
public function login(Request $request)
{
$credentials = $request->validate([
"username" => "required_without:email|exists:users,username",
"emai" => "required_without:username|exists:users,email",
"password" => "required",
]);
if (Auth::attempt($credentials)) {
return view('index');
}
return redirect(route('login'))->withErrors([
"message" => "Usuario o contraseña incorrectos",
]);
}
/** TODO: Document this... */
public function authenticated()
{
return view('index');
}
}
关于你的路由模式,这是正确的,我只是建议你给路由添加一个名称,在我的例子中,我只是使用登录视图名称。
Route::get('/login', [LoginController::class, 'show'])->name("login");
Route::post('/login', [LoginController::class, 'login']);
错误很简单,只需更改视图并将表单方法设置为POST即可。谢谢大家!