Reputation: 77
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 class="fw-normal mb-3 pb-3" style="letter-spacing: 1px;">Log in</h3>
@if ($errors->any())
<div class="alert alert-danger alert-dismissible fade show" role="alert">
<i class="fa-solid fa-triangle-exclamation"></i>
<strong>Error!</strong> Wrong email or password
<button type="button" class="btn-close" data-bs-dismiss="alert"
aria-label="Close"></button>
</div>
@endif
<div class="form-outline mb-4">
<input type="email" name="email" placeholder="Enter a valid email address"
id="email" class="form-control form-control-lg" value="{{ old('email') }}" />
<span class="text-danger">@error('email') {{ $message }} @enderror</span>
</div>
<div class="form-outline mb-4">
<input type="password" name="password" placeholder="Enter password" id="password"
class="form-control form-control-lg" />
<span class="text-danger">@error('password') {{ $message }} @enderror</span>
</div>
<div class="pt-1 mb-4">
<button class="btn btn-primary btn-lg btn-block login-btn"
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'
);
Upvotes: 0
Views: 3272
Reputation: 77
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.
Upvotes: 0
Reputation: 872
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 !
Upvotes: 1