【问题标题】:Laravel : redirect to other url not previous on failed form validationLaravel:在表单验证失败时重定向到其他之前的 url
【发布时间】:2015-06-13 00:18:43
【问题描述】:

注意:我想重定向到以前的网址。

我的注册表单是主页上的一个模式,我将我的表单发布到身份验证/注册,但是当发生验证错误时,它会将我重定向回主页。我想重定向到另一个将显示验证错误的路由“auth/register”。

我经历了 AuthenticatesAndRegistersUsers 、 ValidatesRequests 和 UrlGenerator。我发现它使用标头引用信息将我重定向回以前的 url。

如果发生验证错误,我可以在 AuthenticatesAndRegistersUsers 特征、postRegister 方法中设置什么方法然后这个方法将我重定向到这个特定的 url,而不是使用以前的 url?

【问题讨论】:

    标签: php redirect laravel laravel-5


    【解决方案1】:

    只需编写您自己的postRegister() 方法,并在其中进行您自己的验证和重定向。这就是它的设计方式——因此您可以重载您想要自定义的任何方法。

    【讨论】:

    • 感谢您的建议。不是我所期望的,但解决了我的问题。我期待 laravel 有一些神奇的功能来自定义设置重定向 url 呵呵
    • 如果您使用 FormRequest 验证 - Laravel 确实 具有设置重定向 url 的神奇功能。但它不在 Auth 部分的特征中。
    【解决方案2】:

    我通过修改 AuthenticateAndRegisterUsers.php 文件解决了这个问题:

    \vendor\laravel\framework\src\Illuminate\Foundation\Auth\AuthenticatesAndRegistersUsers.php

    我添加了这一行: return redirect('auth/register')->withErrors($validator);

        public function postRegister(Request $request)
    {
    
        $validator = $this->registrar->validator($request->all());
    
        if ($validator->fails())
        {
            /* $this->throwValidationException(
                $request, $validator
            ); */
            return redirect('auth/register')->withErrors($validator)->withInput();
        }
    
        $this->auth->login($this->registrar->create($request->all()));
    
        return redirect($this->redirectPath());
    }
    

    【讨论】:

    • 这不是标准的,我想你可以在某处覆盖 postRegister 函数。
    • 我强烈建议您不要这样做。一旦您通过 composer update 或 install 更新 laravel,这些文件/代码将被替换。我做了这种修复,所以我不推荐它:)
    • 对,但如果你覆盖 AuthController 中的 postRegister 方法,那将毫无问题地解决问题,除非他们更改了Illumination 中的 postRegister 方法。
    猜你喜欢
    • 2019-07-11
    • 1970-01-01
    • 2013-11-05
    • 1970-01-01
    • 2016-04-03
    • 2018-04-10
    • 2020-12-20
    • 2018-06-13
    • 1970-01-01
    相关资源
    最近更新 更多