duanpie2414 2017-03-19 11:43
浏览 885
已采纳

如何忽略laravel中条件的某些字段的验证

I have an OrderRequest with these rules:

public function rules()
    {
        return [
            //
            'surname' => 'required|max:255',
            'name' => 'required|max:255',
            'city' => 'required|max:255',
            'post_office'=>'required|max:255',
        ];
    }

I need to ignore surname and name validation if request has user_id

Currently doing it this way:

if ((Input::has('user_id'))) {
            return [
                //
                'city' => 'required|max:255',
                'post_office'=>'required|max:255',
            ];
        }
        return [
            //
            'surname' => 'required|max:255',
            'name' => 'required|max:255',
            'city' => 'required|max:255',
            'post_office'=>'required|max:255',
        ];
    }

But can I do it better way and how?

  • 写回答

2条回答 默认 最新

  • duanchou6534 2017-03-19 11:59
    关注

    Since user_id is in your request, you could use required_without. Which requires the field under validation to be present and not empty only when any of the other specified fields are not present.

    return [
                //
                'surname' => 'required_without:user_id|max:255',
                'name' => 'required_without:user_id|required|max:255',
                'city' => 'required|max:255',
                'post_office'=>'required|max:255',
            ];
    

    So now surname and name must be present and not empty only when user_id is not present.


    Also as I said in my comment to Alexey:

    Use Request instead of Input in newer Laravel projects. Input is an alias for request, they resolve the same dependency from the service container but Input is nowhere mentioned in the newer Laravel docs and might be removed in the future. Would be unfortunate if you have to replace all Input with request if you are going to upgrade Laravel ;)

    You can either use the request() helper function or inject the Helper contract or Facade into the constructor / method.

    public function __construct(Request $request)
    {
        $this->request = $request;
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 如何在scanpy上做差异基因和通路富集?
  • ¥20 关于#硬件工程#的问题,请各位专家解答!
  • ¥15 关于#matlab#的问题:期望的系统闭环传递函数为G(s)=wn^2/s^2+2¢wn+wn^2阻尼系数¢=0.707,使系统具有较小的超调量
  • ¥15 FLUENT如何实现在堆积颗粒的上表面加载高斯热源
  • ¥30 截图中的mathematics程序转换成matlab
  • ¥15 动力学代码报错,维度不匹配
  • ¥15 Power query添加列问题
  • ¥50 Kubernetes&Fission&Eleasticsearch
  • ¥15 報錯:Person is not mapped,如何解決?
  • ¥15 c++头文件不能识别CDialog