【问题标题】:Conditionally set a URL to redirect to after authentication有条件地设置一个 URL 以在身份验证后重定向到
【发布时间】:2019-05-28 20:56:29
【问题描述】:

在我的应用中,帖子作者可以将原本公开的帖子设置为私密。如果未经身份验证的用户尝试访问该帖子,系统将提示他们登录。

在他们进行身份验证后,我想将他们重定向回原始帖子 URL,以便他们可以阅读该私人帖子。

这种行为通常由 Laravel 的默认身份验证中间件处理。但是,因为这些帖子通常是公开的,所以我不能在这种情况下使用它。

这是我当前无法运行的中间件:

    public function handle($request, Closure $next)
    {
        $post = $request->route('post');
        if ($post->isPrivate()) {
            $request->session()->setPreviousUrl($request->url());
            return redirect()->guest('login');
        }
        return $next($request);
    }

我希望我可以设置一个自定义 URL 以重定向到 (/posts/{id})。但是,当我尝试登录时,我被重定向到我的默认 $redirectTo 属性 (/dashboard)。

这是可行的吗?我是否以正确的方式思考这个问题?

【问题讨论】:

标签: laravel laravel-5


【解决方案1】:

@adam,感谢您的帮助!

对于其他人来说,这是我的最终代码:

中间件:

    public function handle($request, Closure $next)
    {

        if (auth()->check()) {
            return $next($request);
        }

        $post = $request->route('post');
        if ($post->isPrivate()) {
            $request->session()->setPreviousUrl($request->path());
            return redirect()->guest('login');
        }

        return $next($request);
    }

登录控制器:

    protected function authenticated(Request $request, $user)
    {
        if ($request->session()->has('url.intended')) {
            return redirect($request->session()->get('url.intended'));
        }
    }

【讨论】:

    猜你喜欢
    • 2011-06-23
    • 2017-04-06
    • 1970-01-01
    • 1970-01-01
    • 2017-02-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-12-31
    相关资源
    最近更新 更多