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:11

Laravel >= 5.3

The Auth changes in 5.3 make implementation of this a little easier, and slightly different than 5.2 since the Auth Middleware has been moved to the service container.

Modify the new Middleware auth redirector

/app/Http/Middleware/RedirectIfAuthenticated.php

Change the handle function slightly, so it looks like:

public function handle($request, Closure $next, $guard = null)
{
    if (Auth::guard($guard)->check()) {
        return redirect()->intended('/home');
    }

    return $next($request);
}

TL;DR explanation

The only difference is in the 4th line; by default it looks like this:

return redirect("/home");

Since Laravel >= 5.3 automatically saves the last "intended" route when checking the Auth Guard, it changes to:

return redirect()->intended('/home');

That tells Laravel to redirect to the last intended page before login, otherwise go to "/home" or wherever you'd like to send them by default.

Hope this helps someone else - there's not much out there on the differences between 5.2 and 5.3, and in this area in particular there are quite a few.

查看更多
长期被迫恋爱
3楼-- · 2019-01-02 20:12

For Laravel 5.5 and probably 5.4

In App\Http\Middleware\RedirectIfAuthenticated change redirect('/home') to redirect()->intended('/home') in the handle function:

public function handle($request, Closure $next, $guard = null)
{
    if (Auth::guard($guard)->check()) {
        return redirect()->intended('/home');
    }

    return $next($request);
}

in App\Http\Controllers\Auth\LoginController create the showLoginForm() function as follows:

public function showLoginForm()
{
    if(!session()->has('url.intended'))
    {
        session(['url.intended' => url()->previous()]);
    }
    return view('auth.login');
}

This way if there was an intent for another page it will redirect there otherwise it will redirect home.

查看更多
其实,你不懂
4楼-- · 2019-01-02 20:13

Larvel 5.3 this actually worked for me by just updating LoginController.php

 use Illuminate\Support\Facades\Session;
 use Illuminate\Support\Facades\URL;


public function __construct()
{
    $this->middleware('guest', ['except' => 'logout']);
    Session::set('backUrl', URL::previous());
}


public function redirectTo()
{
    return Session::get('backUrl') ? Session::get('backUrl') :   $this->redirectTo;
}

ref: https://laracasts.com/discuss/channels/laravel/redirect-to-previous-page-after-login

查看更多
回忆,回不去的记忆
5楼-- · 2019-01-02 20:14
       // Also place this code into base controller in contract function,            because ever controller extends base  controller
 if(Auth::id) {
  //here redirect your code or function
 }
if (Auth::guest()) {
       return Redirect::guest('login');
}
查看更多
后来的你喜欢了谁
6楼-- · 2019-01-02 20:15

I found those two great methods that might be extremely helpful to you.

Redirect::guest();
Redirect::intended();

You can apply this filter to the routes that need authentication.

Route::filter('auth', function()
{
    if (Auth::guest()) {
           return Redirect::guest('login');
    }
});

What this method basically does it's to store the page you were trying to visit and it is redirects you to the login page.

When the user is authenticated you can call

return Redirect::intended();

and it's redirects you to the page you were trying to reach at first.

It's a great way to do it although I usually use the below method.

Redirect::back()

You can check this awesome blog.

查看更多
妖精总统
7楼-- · 2019-01-02 20:15

For Laravel 5.2 (previous versions I did not use)

Paste the code into the file app\Http\Controllers\Auth\AurhController.php

   /**
 * Overrides method in class 'AuthenticatesUsers'
 *
 * @return \Illuminate\Contracts\View\Factory|\Illuminate\View\View
 */
public function showLoginForm()
{
    $view = property_exists($this, 'loginView')
        ? $this->loginView : 'auth.authenticate';
    if (view()->exists($view)) {
        return view($view);
    }
    /**
     * seve the previous page in the session
     */
    $previous_url = Session::get('_previous.url');
    $ref = isset($_SERVER['HTTP_REFERER']) ? $_SERVER['HTTP_REFERER'] : '';
    $ref = rtrim($ref, '/');
    if ($previous_url != url('login')) {
        Session::put('referrer', $ref);
        if ($previous_url == $ref) {
            Session::put('url.intended', $ref);
        }
    }
    /**
     * seve the previous page in the session
     * end
     */
    return view('auth.login');
}
/**
 * Overrides method in class 'AuthenticatesUsers'
 *
 * @param Request $request
 * @param $throttles
 *
 * @return \Illuminate\Http\RedirectResponse
 */
protected function handleUserWasAuthenticated(Request $request, $throttles)
{
    if ($throttles) {
        $this->clearLoginAttempts($request);
    }
    if (method_exists($this, 'authenticated')) {
        return $this->authenticated($request, Auth::guard($this->getGuard())->user());
    }
    /*return to the previous page*/
    return redirect()->intended(Session::pull('referrer'));
    /*return redirect()->intended($this->redirectPath()); /*Larevel default*/
}

And import namespace: use Session;

If you have not made any changes to the file app\Http\Controllers\Auth\AurhController.php, you can just replace it with the file from the GitHub

查看更多
登录 后发表回答