can be nullable and must be unique validation in laravel

余生颓废 提交于 2021-02-11 12:33:27

问题


$this->validate($request, [
    'id_num' => 'required | unique:users', //this should be nullable not required with unique.
]);

Is it possible to nullable + unique at a time? then what will be the procedures?


回答1:


Simply remove the required from the validator.

Is it possible to nullable + unique at a time?

Yes

then what will be the procedures?

You don't need a procedure, declare the field as unique in the table migration.

$table->unique('id_num')->nullable();

then your validator must look like:

$this->validate($request, [
    'id_num' => 'unique:users', //this is nullable since it is not required, but it checks for unique
]);



回答2:


id_num can be nullable, if it has value then need to be unique :

$this->validate($request, [
    'id_num' => 'unique:users',
]);

Just remove the required



来源:https://stackoverflow.com/questions/62540477/can-be-nullable-and-must-be-unique-validation-in-laravel

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!