Laravel 5 自定义验证重定向

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/30544779/
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-14 11:40:12  来源:igfitidea点击:

Laravel 5 custom validation redirection

phplaravellaravel-5laravel-routinglaravel-validation

提问by Kenny Yap

I have a website which consist of 2 different login form at 2 places, one on the navbar and the other one is a login page which will be used when the system catches an unlogged visitor.

我有一个网站,它在 2 个地方包含 2 个不同的登录表单,一个在导航栏上,另一个是登录页面,当系统捕获未登录的访问者时将使用该页面。

Can I ask what have I done wrong in my LoginRequest.php where I've set a condition to redirect to a custom login page if there is any sort of error in the login process? I have my codes as below:

如果登录过程中出现任何类型的错误,我可以问我在我的 LoginRequest.php 中做错了什么,我在其中设置了重定向到自定义登录页面的条件吗?我的代码如下:

<?php namespace App\Http\Requests;

use App\Http\Requests\Request;

class LoginRequest extends Request {

    /**
     * Determine if the user is authorized to make this request.
     *
     * @return bool
     */
    public function authorize()
    {
        return true;
    }

    /**
     * Get the validation rules that apply to the request.
     *
     * @return array
     */
    public function rules()
    {
        return [
        'login_email'               =>  'required',
        'login_password'            =>  'required'
        ];
    }


    public function messages()
    {
        return [
            'login_email.required'          =>  'Email cannot be blank',
            'login_password.required'       =>  'Password cannot be blank'
        ];
    }

    public function redirect()
    {
        return redirect()->route('login');
    }
}

The code suppose to redirect users who login from the nav bar if there is any error to the login page but it doesn't seem to redirect.

如果登录页面有任何错误,代码假设重定向从导航栏登录的用户,但它似乎没有重定向。

Thank you.

谢谢你。

采纳答案by Kenny Yap

Found a solutions. All I need to do is to override the initial response from

找到了解决办法。我需要做的就是覆盖来自

FormRequest.php

表单请求.php

like such and it works like a charm.

像这样,它就像一个魅力。

public function response(array $errors)
{
    // Optionally, send a custom response on authorize failure 
    // (default is to just redirect to initial page with errors)
    // 
    // Can return a response, a view, a redirect, or whatever else

    if ($this->ajax() || $this->wantsJson())
    {
        return new JsonResponse($errors, 422);
    }
    return $this->redirector->to('login')
         ->withInput($this->except($this->dontFlash))
         ->withErrors($errors, $this->errorBag);
}

回答by dokko

if you want to redirect to a specific url, then use protected $redirect

如果您想重定向到特定的 url,请使用 protected $redirect

class LoginRequest extends Request
{
    protected $redirect = "/login#form1";

    // ...
}

or if you want to redirect to a named route, then use $redirectRoute

或者如果你想重定向到一个命名的路由,然后使用 $redirectRoute

class LoginRequest extends Request
{
    protected $redirectRoute = "session.login";

    // ...
}

回答by musicvicious

If you are using the validate()method on the Controller

如果您正在使用该validate()方法Controller

$this->validate($request, $rules);

then you can overwrite the buildFailedValidationResponsefrom the ValidatesRequeststrait present on the base Controlleryou extend.

然后你可以覆盖你扩展的基础上存在buildFailedValidationResponseValidatesRequests特征Controller

Something along this line:

沿着这条线的东西:

protected function buildFailedValidationResponse(Request $request, array $errors)
{
    if ($request->expectsJson()) {
        return new JsonResponse($errors, 422);
    }

    return redirect()->route('login');
}

回答by Dillon James Kavanagh

If you do not want to use the validate method on the request, you may create a validator instance manually using the Validator facade. The make method on the facade generates a new validator instance: Refer to Laravel Validation

如果您不想在请求上使用 validate 方法,您可以使用 Validator 外观手动创建一个验证器实例。Facade 上的 make 方法生成一个新的验证器实例:参考Laravel 验证

 public function store(Request $request)
   {
    $validator = Validator::make($request->all(), [
        'title' => 'required|unique:posts|max:255',
        'body' => 'required',
    ]);

    if ($validator->fails()) {
        return redirect('post/create')
                    ->withErrors($validator)
                    ->withInput();
    }

    // Store the blog post...
    }