简体   繁体   中英

How to change the address to be redirected in Laravel

We are developing a new project in Laraveland are currently working on the login section. We currently have two different login forms for authentication.

The first form is in the login (login.blade.php) route. The second one is in the header section . Because of it, we can make the user log in anywhere we want. However, our code that is used for catching errors is in login.blade.php only.

My problem is that if a user makes an authentication error from the second form, I can not catch any error because the code used for catching errors is in login.blade.php.

What I want is that when a user makes an authentication error, I want the user redirected to login.blade.php.

@if(count($errors)>0)
    <div class="alert alert-danger alert-dismissible fade show" role="alert">
        <strong>Bir Hata Meydana Geldi!</strong>
        <ul class="list-group">
            @foreach($errors->all() as $error)
                <li class="list-group-item">{{$error}}</li>
            @endforeach
        </ul>
    </div>
@endif

MY LOGIN FORMS

Is there any way to do it?

In your login controller, you can specify the view you want to return the user to. Along with that, you can also pass the validation errors encountered, if any. Then it doesn't matter if the user tries to log in via your header form or your login page form, it'll always be redirected to the login view.

        return view('login', array(
            'data' => $data,
            'errors' => $validator->errors()
        ));

Laravel will automatically redirect you back to the last URL if a validation failure occurs. So if you try and log in from the header from the URI /foo and the request fails validation, then Laravel will redirect you back to /foo with the errors in the session.

Instead, you should probably use AJAX in the login form in your header. When the user enters their email and password, make the request via AJAX. You'll then get a JSON response. If the login request was successful, you'll get a 2xx range response and can reload the page (the user will then be authenticated and you can hide the login form). If there was an error, you'll get a 422 response and the validation errors messages back then you can then inject into your form's mark-up.

This way, your “traditional” login form on /login will continue to work as expected, and your “header” login form will work on whatever page the user tries to log in on.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM