Check if name is unique among non-deleted items with laravel validation

后端 未结 5 755
走了就别回头了
走了就别回头了 2020-12-05 14:06

I have a simple form which posts to a controller which checks if a name for an item is already taken for a particular project. If it is, then it returns an error. This is th

5条回答
  •  春和景丽
    2020-12-05 14:39

    You may try this:

    'name' => 'required|min:1|unique:versions,name,NULL,id,deleted_at,NULL'
    

    This will make sure that the name in the versions table will be unique, if a record is soft deleted and has same name name then it won't be counted, means, name will be accepted even if there is a soft deleted record with the same name exists.

    To ignore a model when updating, you should pass the id after name in the place of first NULL.

    Update: Also you may use something like this to add your own custom rule:

    // You can declare it inside your controller method before you run validation
    Validator::extend('unique_project', function($attribute, $value, $parameters)
    {
       // $attribute will contain field name, i.e. name
       // $value will contain the value in the $attribute/name
       // $parameters will be an array of arguments passed
       // i.e. [0] => arg1, [1] => arg2, [2] => arg3 and so on
    
       return true for valid and false for invalid
    
    });
    

    You may use it like this:

    'name' => 'required|min:1|unique_project:arg1,arg2,arg3' // add more args if needed
    

提交回复
热议问题