Laravel登录验证失败时,如何实现控制器与视图关联触发模态框?
Hey Felipe, let's work through this together! You've got a great start with your login form and modal—we just need to connect the dots between the controller and view to trigger that modal when credentials are wrong. You don't have to use AJAX, but it's an option depending on how you want the user experience to feel. Let's cover both approaches:
Approach 1: Traditional (No AJAX, Using Laravel Flash Sessions)
This method uses Laravel's session flash messages to pass the error state back to the login view, then triggers the modal with JavaScript when the page loads.
Step 1: Update Your Controller
First, fix your logar method to validate both fields properly, and flash an error state to the session when login fails:
public function login() { return view('login'); } public function logar(Request $req) { // Validate both email and password are required $req->validate([ 'email' => ['required', 'email'], 'password' => ['required'] ]); // Use only() to safely grab the necessary credentials $credentials = $req->only('email', 'password'); if (Auth::attempt($credentials)) { // Login success: redirect to shop index return redirect()->route('shop.index'); } // Login failed: flash error state and redirect back to login return redirect()->route('shop.login') ->with('login_failed', true); }
Step 2: Trigger the Modal in Your View
Add a small script block to your login view that checks for the flashed session value and shows the modal if it exists. Make sure you have jQuery and Bootstrap JS included (the modal relies on them):
<form class="login-form needs-validation" method="POST" action="{{ route('loja.logar') }}" novalidate> @csrf <div class="form-group"> <input type="email" class="form-control w-50 mx-auto my-0 py-4" id="email" name="email" aria-describedby="emailHelp" placeholder="Email" required> </div> <div class="form-group"> <input type="password" class="form-control w-50 mx-auto my-0 py-4" id="password" name="password" placeholder="Senha" required> </div> <button type="submit" id="submit" name="submit" class="btn btn-outline-primary mt-2 py-3 px-4">Enviar</button> </form> <div class="modal fade" id="modal1" tabindex="-1" role="dialog" aria-labelledby="exampleModalCenterTitle" aria-hidden="true"> <div class="modal-dialog modal-dialog-centered" role="document"> <div class="modal-content"> <div class="modal-header"> <h5 class="modal-title" id="exampleModalCenterTitle">Error</h5> </div> <div class="modal-body"> Login or password incorrect! Try again. </div> </div> </div> </div> <!-- Check for login error and show modal --> @if(session('login_failed')) <script> document.addEventListener('DOMContentLoaded', function() { $('#modal1').modal('show'); }); </script> @endif
Approach 2: AJAX (No Page Refresh)
If you want a smoother experience without reloading the page, use AJAX to submit the form asynchronously.
Step 1: Modify the Form and Add AJAX Script
Update your form to prevent default submission, then use jQuery to send the data to your controller:
<form class="login-form needs-validation" id="loginForm" novalidate> @csrf <div class="form-group"> <input type="email" class="form-control w-50 mx-auto my-0 py-4" id="email" name="email" aria-describedby="emailHelp" placeholder="Email" required> </div> <div class="form-group"> <input type="password" class="form-control w-50 mx-auto my-0 py-4" id="password" name="password" placeholder="Senha" required> </div> <button type="submit" id="submit" name="submit" class="btn btn-outline-primary mt-2 py-3 px-4">Enviar</button> </form> <div class="modal fade" id="modal1" tabindex="-1" role="dialog" aria-labelledby="exampleModalCenterTitle" aria-hidden="true"> <div class="modal-dialog modal-dialog-centered" role="document"> <div class="modal-content"> <div class="modal-header"> <h5 class="modal-title" id="exampleModalCenterTitle">Error</h5> </div> <div class="modal-body"> Login or password incorrect! Try again. </div> </div> </div> </div> <script> $(document).ready(function() { $('#loginForm').on('submit', function(e) { e.preventDefault(); // Stop the form from reloading the page $.ajax({ url: "{{ route('loja.logar') }}", method: 'POST', data: $(this).serialize(), // Serialize form data into a URL-encoded string success: function() { // Redirect to shop index on successful login window.location.href = "{{ route('shop.index') }}"; }, error: function() { // Show error modal if login fails $('#modal1').modal('show'); } }); }); }); </script>
Step 2: Update the Controller to Return JSON Responses
Modify your logar method to send JSON instead of redirects, since we're using AJAX:
public function logar(Request $req) { $req->validate([ 'email' => ['required', 'email'], 'password' => ['required'] ]); $credentials = $req->only('email', 'password'); if (Auth::attempt($credentials)) { return response()->json(['success' => true], 200); } return response()->json(['error' => 'Invalid credentials'], 401); }
Quick Notes
- Make sure your project includes jQuery and Bootstrap JS—the modal won't function properly without them.
- The traditional method is simpler and works without extra JS setup, while AJAX provides a more seamless, modern user experience.
内容的提问来源于stack exchange,提问作者Felipe Moreira

