Laravel redirect back to original destination afte

2019-01-02 19:58发布

This seems like a pretty basic flow, and Laravel has so many nice solutions for basic things, I feel like I'm missing something.

A user clicks a link that requires authentication. Laravel's auth filter kicks in and routes them to a login page. User logs in, then goes to the original page they were trying to get to before the 'auth' filter kicked in.

Is there a good way to know what page they were trying to get to originally? Since Laravel is the one intercepting the request, I didn't know if it keeps track somewhere for easy routing after the user logs in.

If not, I'd be curious to hear how some of you have implemented this manually.

18条回答
无色无味的生活
2楼-- · 2019-01-02 20:17

Laravel 3

I tweaked your (Vinícius Fragoso Pinheiro) code slightly, and placed the following in filters.php

Route::filter('auth', function()
{
    // If there's no user authenticated session
    if (Auth::guest()) {
        // Flash current url to session and redirect to login page
        Session::flash('redirect', URL::full());
        return Redirect::guest('login');
    }
});

And then within the my AuthController.php:

// Try to log the user in.
if (Auth::attempt($userdata)) {

    if ($redirect = Session::get('redirect')) {
        return Redirect::to($redirect);
    } else {
        // Redirect to homepage
        return Redirect::to('your_default_logged_in_page')->with('success', 'You have logged in successfully');
    }
} else {
    // Reflash the session data in case we are in the middle of a redirect 
    Session::reflash('redirect');

    // Redirect to the login page.
    return Redirect::to('login')->withErrors(['password' => 'Password invalid'])->withInput(Input::except('password'));
}

Notice that the 'redirect' session data is reflashed if there is a authentication issue. This keeps the redirect intact during any login mishaps, but should the user click away at any point, the next login process is not disrupted by the session data.

You also need to reflash the data at the point of showing the login form in your AuthController, otherwise the chain is broken:

public function showLogin()
{
    // Reflash the session data in case we are in the middle of a redirect 
    Session::reflash('redirect');

    // Show the login page
    return View::make('auth/login');
}
查看更多
看风景的人
3楼-- · 2019-01-02 20:17

Laravel 5.2

If you are using a another Middleware like Admin middleware you can set a session for url.intended by using this following:

Basically we need to set manually \Session::put('url.intended', \URL::full()); for redirect.

Example

  if (\Auth::guard($guard)->guest()) {
      if ($request->ajax() || $request->wantsJson()) {
         return response('Unauthorized.', 401);
      } else {
        \Session::put('url.intended', \URL::full());
        return redirect('login');
      }
  }

On login attempt

Make sure on login attempt use return \Redirect::intended('default_path');

查看更多
后来的你喜欢了谁
4楼-- · 2019-01-02 20:20

Use Redirect;

Then use this:

return Redirect::back();
查看更多
不再属于我。
5楼-- · 2019-01-02 20:22

I have been using this for a while on my language selector code. As long as you only need to go back by just 1 page it works fine:

return Redirect::to(URL::previous());

It ain't the most powerful solution out there but it is super-easy and can help solve a few puzzles. :)

查看更多
忆尘夕之涩
6楼-- · 2019-01-02 20:24

Change your LoginControllers constructor to:

public function __construct()
    {
        session(['url.intended' => url()->previous()]);
        $this->redirectTo = session()->get('url.intended');

        $this->middleware('guest')->except('logout');
    }

It will redirect you back to the page BEFORE the login page (2 pages back).

查看更多
余欢
7楼-- · 2019-01-02 20:26

For Laravel 5.3 and above

Check Scott's answer below.

For Laravel 5 up to 5.2

Simply put,

On auth middleware:

// redirect the user to "/login"
// and stores the url being accessed on session
if (Auth::guest()) {
    return redirect()->guest('login');
}
return $next($request);

On login action:

// redirect the user back to the intended page
// or defaultpage if there isn't one
if (Auth::attempt(['email' => $email, 'password' => $password])) {
    return redirect()->intended('defaultpage');
}

For Laravel 4 (old answer)

At the time of this answer there was no official support from the framework itself. Nowadays you can use the method pointed out by bgdrl below this method: (I've tried updating his answer, but it seems he won't accept)

On auth filter:

// redirect the user to "/login"
// and stores the url being accessed on session
Route::filter('auth', function() {
    if (Auth::guest()) {
        return Redirect::guest('login');
    }
});

On login action:

// redirect the user back to the intended page
// or defaultpage if there isn't one
if (Auth::attempt(['email' => $email, 'password' => $password])) {
    return Redirect::intended('defaultpage');
}

For Laravel 3 (even older answer)

You could implement it like this:

Route::filter('auth', function() {
    // If there's no user authenticated session
    if (Auth::guest()) {
        // Stores current url on session and redirect to login page
        Session::put('redirect', URL::full());
        return Redirect::to('/login');
    }
    if ($redirect = Session::get('redirect')) {
        Session::forget('redirect');
        return Redirect::to($redirect);
    }
});
// on controller
public function get_login()
{
    $this->layout->nest('content', 'auth.login'); 
}

public function post_login()
{
    $credentials = [
        'username' => Input::get('email'),
        'password' => Input::get('password')
    ];

    if (Auth::attempt($credentials)) {
        return Redirect::to('logged_in_homepage_here');
    }

    return Redirect::to('login')->with_input();
}

Storing the redirection on Session has the benefit of persisting it even if the user miss typed his credentials or he doesn't have an account and has to signup.

This also allows for anything else besides Auth to set a redirect on session and it will work magically.

查看更多
登录 后发表回答