duanpie2414 2017-03-19 11:43 采纳率: 100%
浏览 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条)

报告相同问题?