简体   繁体   中英

How to ignore validation of some fields with condition in 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?

我猜想使用三元运算符和request()助手将是一个更好的方法:

'surname' => request()->has('user_id') ? '' : 'required|max:255',

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM