【问题标题】:Laravel custom redirection after validation errors验证错误后的 Laravel 自定义重定向
【发布时间】:2015-08-13 05:13:01
【问题描述】:

请问我在我的 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');
    }
}

如果有任何错误,该代码应该将从导航栏登录表单登录的用户重定向到主登录页面,但它似乎没有重定向。

【问题讨论】:

    标签: php laravel laravel-validation


    【解决方案1】:

    如果你想重定向到特定的 url,那么使用protected $redirect

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

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

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

    【讨论】:

    • 其实在L5.4完全有效
    • 在 L5.8 中仍然有效
    • “缺少 [Route: restaurant-update-images.user] [URI: panel/restaurant/update-images/{user}] 所需的参数。”在 Laravel 5.7 为什么?
    【解决方案2】:

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

    的初始响应

    FormRequest.php

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

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

    【讨论】:

    • 很好的答案。 array 参数在结构上类似于 $errors = $validator-&gt;errors() 的输出(但 $errors->all() 等方法可能不太适用)。因此,要将所有错误作为数组获取,请使用辅助函数 array_flatten($errors)
    【解决方案3】:

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

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

    【讨论】:

      【解决方案4】:

      这适用于 Lara 7 如果验证失败,添加锚点以跳转到评论表单

      protected function getRedirectUrl()
      {
          return parent::getRedirectUrl() . '#comment-form';
      }
      

      【讨论】:

        【解决方案5】:

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

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

        然后您可以从您扩展的基础Controller 上存在的ValidatesRequests 特征覆盖buildFailedValidationResponse

        类似的东西:

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

        【讨论】:

          【解决方案6】:

          已经提供了此答案的变体,但在 custom request 中覆盖 getRedirectUrl() 方法可以让您定义路由参数,而不仅仅是 $redirectRoute 属性提供的名称。

          【讨论】:

            猜你喜欢
            • 1970-01-01
            • 2017-01-24
            • 2021-01-12
            • 2014-04-05
            • 2016-04-02
            • 2018-10-23
            • 1970-01-01
            • 1970-01-01
            • 2016-10-21
            相关资源
            最近更新 更多