登录后 Laravel 重定向回原始目的地

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/15389833/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-09 02:24:07  来源:igfitidea点击:

Laravel redirect back to original destination after login

laravellaravel-4

提问by JOV

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

这似乎是一个非常基本的流程,并且Laravel对于基本的事情有很多很好的解决方案,我觉得我错过了一些东西。

A user clicks a link that requires authentication. Laravel's authfilter 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.

用户单击需要身份验证的链接。Laravel 的身份验证过滤器启动并将它们路由到登录页面。用户登录,然后转到他们试图在“身份验证”过滤器启动之前访问的原始页面。

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.

有什么好方法可以知道他们最初试图访问哪个页面?由于 Laravel 是拦截请求的那个,我不知道它是否会在用户登录后跟踪某处以便于路由。

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

如果没有,我很想知道你们中的一些人是如何手动实现的。

回答by vFragosop

For Laravel 5.3 and above

对于 Laravel 5.3 及更高版本

Check Scott's answerbelow.

检查下面斯科特的答案

For Laravel 5 up to 5.2

对于 Laravel 5 到 5.2

Simply put,

简单的说,

On auth middleware:

在 auth 中间件上:

// 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)

对于 Laravel 4(旧答案)

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 belowthis method: (I've tried updating his answer, but it seems he won't accept)

在回答这个问题时,框架本身没有官方支持。现在你可以使用下面bgdrl指出的方法这种方法:(我已经尝试更新他的答案,但似乎他不会接受)

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)

对于 Laravel 3(甚至更旧的答案)

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.

将重定向存储在 Session 上的好处是,即使用户没有输入他的凭据或者他没有帐户并且必须注册,它也可以保留它。

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

这也允许除了 Auth 之外的任何其他东西在会话上设置重定向,它会神奇地工作。

回答by Scott Byers

Laravel >= 5.3

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.

5.3 中的 Auth 更改使此实现更容易一些,并且与 5.2 略有不同,因为 Auth 中间件已移至服务容器。

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

TL; DR 解释

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

唯一的区别在第 4 行;默认情况下,它看起来像这样:

return redirect("/home");

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

由于 Laravel >= 5.3 在检查 Auth Guard 时会自动保存最后一个“预期”的路由,它更改为:

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.

这告诉 Laravel 在登录前重定向到最后一个预期页面,否则转到“/home”或默认情况下您想发送它们的任何位置。

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.

希望这对其他人有所帮助 - 5.2 和 5.3 之间的差异并不多,特别是在这方面有很多。

回答by giannis christofakis

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 loginpage.

此方法的主要作用是存储您尝试访问的页面,并将您重定向到登录页面。

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 thisawesome blog.

你可以查看这个很棒的博客。

回答by dabuno

You may use Redirect::intendedfunction. It will redirect the user to the URL they were trying to access before being caught by the authenticaton filter. A fallback URI may be given to this method in case the intended destinaton is not available.

您可以使用Redirect::intended函数。它会将用户重定向到他们在被身份验证过滤器捕获之前尝试访问的 URL。如果预期的目的地不可用,则可以为此方法提供回退 URI。

In post login/register:

在登录/注册后:

return Redirect::intended('defaultpageafterlogin');

回答by Federico Stango

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:

我已经在我的语言选择器代码上使用了一段时间。只要您只需要返回 1 页,它就可以正常工作:

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. :)

它不是最强大的解决方案,但它非常简单,可以帮助解决一些难题。:)

回答by Mevlüt?zdemir

Change your LoginControllers constructor to:

将您的 LoginControllers 构造函数更改为:

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).

它会将您重定向回登录页面之前的页面(返回 2 页)。

回答by Parag Bhingre

return Redirect::intended('/');

this will redirect you to default page of your project i.e. start page.

这会将您重定向到项目的默认页面,即开始页面。

回答by Nuruzzaman Milon

For laravel 5.* try these.

对于 laravel 5.* 试试这些。

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

or

或者

return Redirect::intended('/');

回答by Joe Richards

Laravel 3

Laravel 3

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

我稍微调整了您的 (Vinícius Fragoso Pinheiro) 代码,并将以下内容放入 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:

然后在我的 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.

请注意,'redirect'如果存在身份验证问题,会话数据会重新刷新。这可以在任何登录事故期间保持重定向不变,但如果用户在任何时候点击离开,下一个登录过程不会被会话数据中断。

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

您还需要在您的 中显示登录表单时重新刷新数据AuthController,否则链会中断:

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');
}

回答by ujwal dhakal

Use Redirect;

Redirect;

Then use this:

然后使用这个:

return Redirect::back();