0
votes

I made a login and register modal with Laravel Auth and materializecss modals (They work the same as Bootstrap modals). Everything works fine except one thing.

There is a check when I submit my form for several thing: Do the email and password match? Does the email exist in the database etc.

When one of the checks fails the user will not login and an error will be stored in the php array: $errors.

The problem is that the modal closes when the form submits, which is fine when the login is good. But when the login fails and a error appears. Than the modal should be reopened and the error must be shown in the modal.

I tried many things but I don't have much experience with JS and jQuery. I hope somebody can help and explain how it works?

I solved the problem with this code:

    if ($('div#login-email').hasClass('has-error')) {
        $('#login-modal').modal('open');
    }

    if ($('div#login-password').hasClass('has-error')) {
        $('#login-modal').modal('open');
    }

Laravel adds a has-error class to the form-group where you did something wrong. So when there are no divs with the class: has-error, than everything is fine.

When there is a div with the class has-error, than you failed at some point. So the modal should re-open.

3
Using preventDefault would probably stop the modal from closing when using a proper ajax call. At the moment you're telling the form to submit which i'm assuming is closing your modal. Have a look into utilising ajax properly :) - Andy Holmes
I can't understand why people using forms anymore. If you use ajax just pass a json object collected from fields. why going through the trouble of form and submit? they had a purpose in the pre-ajax days, but now it is over. - Aus
Personally, I won't recommend AJAX for the login page, it will have a lot implications that should be taken care of specially for the tokens part, cookies... - Mina Abadir
I found something about the login / register from Laravel Auth and found another way to solve my problem. I've added the code in my question. Thanks everyone for helping! - Nieck

3 Answers

1
votes

you need to reopen the model out of form submit event because that code is only executed when form submit.

var errors = {{$errors->all()}};
$(function() {
    if(errors.length) {

         alert('There is an error!');

         $('#modal').modal('open');
     }
});
0
votes

you need to add the code in your blade page

@if (session('openLogin') || Session::has('errors'))
        <script>
            $('#modalLogin').modal('show');
        </script>
@endif

and in web.php

Route::get('auth/login',function () {

    return redirect('/')->with('openLogin',true);

});
0
votes

Just add this code on your blade page to verify if exists errors and reopen the modal form.

@if ($error = $errors->first('email'))
  <script>
    $(document).ready(function() {
      $("#myModal").modal("show");
    });
  </script>
@endif