繁体   English   中英

如何在登录前返回重定向返回页面 | Laravel 8.83.23

[英]How to Return Redirect Back To Page Before Login | Laravel 8.83.23

我有一个 laravel 应用程序版本 8.83.23。 我有多个视图,其中包含显示登录页面的链接。 一个简单的例子是这样的:

想想一篇博文。 “您必须登录才能发表评论”.. 用户单击“登录”并进入登录视图 (auth.login)。 用户填写表格并提交。 用户已通过身份验证。 然后,我希望将经过身份验证的用户重定向到他们最初单击登录的页面。

这个概念

是否有一个简单的解决方案,例如将 LoginController.php 中的 $redirectTo 更改为动态的东西?

如果要重定向回用户登录的页面

return back();

我通常使用它的方式是使用Laravel intended方法

Laravel 的重定向器提供的intended方法会将用户重定向到他们在被身份验证中间件拦截之前尝试访问的 URL。 如果预期的目的地不可用,则可以为此方法提供后备 URI。

We are setting the url.intended value in the current session so when the user visits the login page, it will check for the url.intended to redirect the user where they were when they clicked the login URL. 如果没有url.intended它只会重定向到默认的RouteServiceProvider::HOME

AuthenticatedSessionController.php 存储方法是 Laravel 8.83.1 中的惯性脚手架附带的存储方法(不确定此后是否发生了变化)

MyController.php

class QuotesController extends Controller
{
    public function productQuote(string $product)
    {
        if (auth()->guest()) {
            session()->put('url.intended', request()->fullUrl());
        }

        return view(
            'get-product-quote',
            ['product' => $this->getProduct($product), 'user' => $this->getUser()]
        );
    }
}

get-product-quote视图中,我只是这样做:

<x-app-layout>
    <div class="relative container mx-auto z-0 py-8 px-4 sm:px-6 lg:px-8">
        @guest
            <div>
                <a :href="route('login')" class="inline-block py-3 px-8 bg-itg-blue hover:bg-itg-blue-dark border border-transparent text-white text-sm rounded-sm text-center">Log in for faster quote submitting process</a>
            </div>
        @endguest

        @auth
            ... 
            <p>do the authenticated user stuff</p>
        @endauth
    </div>
</x-app-layout>

AuthenticatedSessionController.php

class AuthenticatedSessionController extends Controller
{
    /**
     * Handle an incoming authentication request.
     *
     * @param  \App\Http\Requests\Auth\LoginRequest  $request
     * @return \Illuminate\Http\RedirectResponse
     */
    public function store(LoginRequest $request)
    {
        $request->authenticate();

        $request->session()->regenerate();

        return redirect()->intended(RouteServiceProvider::HOME);
    }
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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