Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Laravel Ajax login, redirect to previous url after success

Suppose I have a page A where auth middleware is being used. Because of no login it gets redirected to login page.

On login page I have custom ajax login system. On succesful login I want to redirect to page A with same url so that action can be completed.

My code for login is like this:

public function postLogin(Request $request)
{

    $auth = false;
    $errors = [];

    $inputs = $request->all();
    $validator = $this->validator($inputs);

    if ($validator->fails()) {
        return response()->json([
            'auth' => false,
            'intended' => URL::previous(),
            'errors' => $validator->errors()
        ]);
    }

    $user = User::where('email', $request->get('email'))->first();

    if ($user && $user->is_active == 0) {
        $errors[] = "This account has been deactivated";
    } else if ($user && $user->confirm_token != null) {
        $errors[] = "Please verify your email in order to login";
    } else {

        $credentials = ['email' => $request->get('email'), 'password' => $request->get('password'), 'is_active' => 1];

        if (Auth::attempt($credentials, $request->has('remember'))) {
            $auth = true;
        } else {
            $errors[] = "Email/Password combination not correct";
        }

    }

    if ($request->ajax()) {          
        return response()->json([
            'auth' => $auth,
            'intended' => URL::previous(),
            'errors' => $errors
        ]);
    }

    return redirect()->intended(URL::route('dashboard'));

}

I am trying to get previous url through url()->previous() but it returns login page url. Can someone guide me in this please. Any improvements/help will be appreciated.

I am using Laravel 5.4

like image 988
Waleed Avatar asked Jun 11 '18 09:06

Waleed


People also ask

How to redirect back to previous page after login in Laravel?

In this laravel tutorial, you will learn how to redirect back to previous page or url after login in laravel apps. This tutorial provides you two methods to redirect user back to previous url or page after login in laravel apps. Go to your loginContorller and open it. Then add this showLoginForm () function code as follow:

How to redirect back to previous page after login in WordPress?

Build the redirecting back to previous page using login.php. Grabbing the previous URL from the login page inside the LoginController.php and Redirect. We need to make some tweaks in order to get the previous URL and redirect back to the page where the visitor comes from after logging in.

How does login page work in Laravel?

In your case your login page is initiating the request to your login handler, via AJAX. When you try to visit a page protected by Laravel's auth middleare, it is at that point Laravel sets a value for the intended URL in the session, before redirecting you to the login page.

How to get the previous url from the login page?

Grabbing the previous URL from the login page inside the LoginController.php and Redirect. We need to make some tweaks in order to get the previous URL and redirect back to the page where the visitor comes from after logging in. So we will make some changes in the login.blade.php


5 Answers

I have a very similar problem here: Ajax Auth redirect on Laravel 5.6

As @aimme (https://stackoverflow.com/users/1409707/aimme) pointed out, Ajax calls are stateless, so basically you can't interact with backend.

His suggestion and my suggestion is to pass in the URL the intended page to redirect to, or maybe in your case you could to it via post parameters, e.g.:

return response()->json([
    'auth' => false,
    'intended' => $request->intended,
    'errors' => $validator->errors()
]);
like image 83
Marco Cazzaro Avatar answered Oct 17 '22 05:10

Marco Cazzaro


It might help you

Instead of these return redirect()->intended(URL::route('dashboard'));

use

return redirect('dashboard');
like image 30
Deepak Avatar answered Oct 17 '22 03:10

Deepak


There is no need to do anything special for AJAX calls.

Redirect the same way you normally would on the back-end after a form submission.

return redirect()->route('dashboard');

On the front-end you just need to be sure that you use the redirected URL to change the window.location. This will cause the browser to refresh and go to the new page.

axios.post(url, formData).then(response => {
    window.location = response.request.responseURL;
});

This code snippet is for the popular Axios library but the same thing can be done with jQuery or vanilla JavaScript.

like image 43
Erik Berkun-Drevnig Avatar answered Oct 17 '22 05:10

Erik Berkun-Drevnig


Laravel 5.4 + support . not know for lower version

 return redirect()->back();

This will redirect to previous page from where you came .

Ajax part

 <script type="text/javascript">
    var url = "<?php echo url()->previous(); ?>";
    location.href = url;
 </script>

                OR simply javascript function
 history.go(-1);

Check for above and working fine for me please check for your code .

like image 3
Affan Avatar answered Oct 17 '22 05:10

Affan


If I understand your problem correctly, the problem is that you're confusing the previous URL for the intended URL when you're trying to provide a URL to redirect to in your JSON response. The previous URL actually refers to the HTTP Referrer, not the intended URL, which is set in the session by Laravel's auth middleware.

The HTTP referrer is the page that initiates a request. If you are currently on page /foo and you click a link to a page /bar, the HTTP Referrer on /bar will be /foo. The same thing happens when you initiate an AJAX request, the page you're on will be the referrer of the end point you're hitting. In your case your login page is initiating the request to your login handler, via AJAX.

When you try to visit a page protected by Laravel's auth middleare, it is at that point Laravel sets a value for the intended URL in the session, before redirecting you to the login page. Laravel stores the intended URL in the session as url.intended (As you will be able to see in Illuminate\Routing\Redirector::intended, which is what redirect()->intended() calls). So all you need to do is grab that from the session.

if ($request->ajax()) {          
    return response()->json([
        'auth' => $auth,
        'intended' => session()->pull('url.intended') ?: URL::route('dashboard'),
        'errors' => $errors
    ]);
}

return redirect()->intended(URL::route('dashboard'));

Note: Using ->pull will remove the item from the session after it has been retrieved.

An easier way to do this would be just to grab the target URL from an intended RedirectResponse:

$redirect = redirect()->intended(URL::route('dashboard'))

if ($request->ajax()) {          
    return response()->json([
        'auth' => $auth,
        'intended' => $redirect->getTargetUrl(),
        'errors' => $errors
    ]);
}

return $redirect;
like image 2
Jonathon Avatar answered Oct 17 '22 05:10

Jonathon