I am trying to create a simple login form. When I press the login button a request is sent to my controller where I can see the data being received by dd($request); . But when I validate the data if the data is not correct the page starts to reload and keeps on reloading itself.
Controller:
class UserController extends Controller
{
public function loginView()
{
return view('admin-login');
}
public function userLogin(Request $request)
{
$request->validate([
'email' => 'required|email',
'password' => 'required|alphaNum|min:8',
]);
$user_data = [
'email' => $request->get('email'),
'password' => $request->get('password'),
];
if (Auth::attempt($user_data)) {
return redirect('/admin');
} else {
return back()->with('error', 'Wrong email or password');
}
}
}
Login Form:
<form style="width: 23rem;" action="{{ route('login.custom') }}" method="post">
@csrf
<h3 style="letter-spacing: 1px;">Log in</h3>
@if ($errors->any())
<div role="alert">
<i ></i>
<strong>Error!</strong> Wrong email or password
<button type="button" data-bs-dismiss="alert"
aria-label="Close"></button>
</div>
@endif
<div >
<input type="email" name="email" placeholder="Enter a valid email address"
id="email" value="{{ old('email') }}" />
<span >@error('email') {{ $message }} @enderror</span>
</div>
<div >
<input type="password" name="password" placeholder="Enter password" id="password"
/>
<span >@error('password') {{ $message }} @enderror</span>
</div>
<div >
<button
type="submit">Login</button>
</div>
</form>
Route:
Route::get('/login', [UserController::class, 'loginView'])->name('login');
Route::post('custom-login', [UserController::class, 'userLogin'])->name(
'login.custom'
);
CodePudding user response:
Try this
if (Auth::check()) { // use this instead of Auth::attempt($user_data)
return redirect('/admin');
} else {
return back()->with('error', 'Wrong email or password');
}
i hope it was useful !
CodePudding user response:
Solution:
I was using Live Server extension from VS Code to auto refresh the page. This extension was reloading the page again and again after redirect. So, now after turning it off everything works fine.