Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

MahmoudAdelAli's avatar

How to show form modal when validation return error

Hi , i have 3 form modals at same page [Register Teachers, login Students , Register Teachers] so for now i need if there's validation error i show this modal with errors i using @error directive to show the error fro each input and it works but i can't show the modal - at login i used this way

#blade
   @if ($errors->has('username_login'))
                window.onload = function () {
                $('#loginModal').modal('show');

            }
            @endif
#controller
  public function login(LoginRequest $request)
    {

        $credentials = $request->validated();
        if (AUTH::guard('student')->attempt($credentials,$request->remember))
        {
            return redirect()->back();
        }
        return redirect()->back()->withInput($request->only('username'))->withErrors([
            'username_login' => __('login_error'),
        ]);

    }

but at register validation the logic is different cause that validation not able to do anything after validate

#Register controller 
public function store(RegisterRequest $request) {

        $attributes = $request->validated();
        $attributes['created_by'] = __('platform');
        $attributes['avatar'] = (new Mediaable($request))
            ->moveToDir("images/teachers/waiting/${attributes['username']}/photo")
            ->getMediaFromRequestByName('avatar')
            ->getMediaNameAfterUpload();
        if($request->has('cv'))
        {
            $attributes['cv'] = (new Mediaable($request))
                ->moveToDir("images/teachers/waiting/${attributes['username']}/cv")
                ->getMediaFromRequestByName('cv')
                ->getMediaNameAfterUpload();
        }


        $teacher = Teacher::create($attributes);
        if (!$teacher) {
            return redirect()->back()->with('error', 'Error message goes here');
        }

        return redirect()->route('teacherLogin')->with('success', __('messages.has_joined'));
    }

so if i used $errors->any() that may caused all modals open cause no specific parameters tells me which form and cause i using custom rules request validation i can't using ->fails() or something like .

0 likes
6 replies
jlrdw's avatar

Return as json and loop and display. I show in a division.

1 like
jlrdw's avatar

@MahmoudAdelAli

                .catch(error => {
                    console.error('Error:', error);
                    var div = document.getElementById('msg');
                    for (var key in error) {
                        div.innerHTML += error[key];
                    }
        if ($validator->fails()) {
            return response()->json($validator->errors(), 422);

Something like that.

Also for a general error:

                    .catch((error) => {
                        console.error('Error:', error);
                        document.getElementById('msg').innerHTML = "An error occured";
                    });
1 like
MahmoudAdelAli's avatar

@jlrdw

if ($validator->fails()) { return response()->json($validator->errors(), 422); 'll not work

jlrdw's avatar

@MahmoudAdelAli are you using your developer tools to see what you are actually returning.

Edit:

Just done quick, not formatted good, but I placed error in a modal:

Alt image

Adapt to your javascript as needed.

                        if (response.status === 422) {
                            response.json().then(function (data) {
                                var div = document.getElementById('msg');
                                var modal = document.getElementById("myModal");
                                var span = document.getElementsByClassName("close")[0];
                                document.getElementById("myModal").style.display = "block";
                                //document.getElementById("myModal").style.height = "100%";
                                var somediv = document.getElementById("somediv");
                                for (var key in data) {
                                    somediv.innerHTML += data[key];
                                }
                            })
                        }

Adapt to your modal.

1 like
Snapey's avatar
Snapey
Best Answer
Level 122

I've done this before on an old site, and I've been trying to refresh my memory about how it works.

One of the key things is to have a hidden field on the form which contains the name of the modal so that if a validation error occurs, the returned data (the old() data contains a field that has the name of the modal)

so, in the form I have

<input type="hidden" name="modal" value="login-modal" />

And then on the page with the modal, the following javascript;

  {{--  check for a failed login and re-show the login modal--}}
  <script>
    @if(old('modal')) 
      $(window).load(function(){
        $('#{{ old('modal') }}').modal('show');
      });
    @else

      <?php 
        if(isset($modal)) {
          echo('$(window).load(function(){$("#' . $modal . '").modal(\'show\');});');
        }          
      ?>

    @endif
  </script>

So if old('modal') contains a value, then call modal show on the element with the same name as in the form value

The second part of the code is where I want to come from another page and show the login modal automatically. The $modal parameter is passed from the controller, and if it is set, then show the modal.

If you are interested, the site is here: https://rotarota.net/. You can try logging in with false details, or register and don't complete the form.

1 like

Please or to participate in this conversation.