Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
507 views
in Technique[技术] by (71.8m points)

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

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 the code I'm using for that:

'name'    => 'required|min:1|unique:versions,name,NULL,id,project_id,'.$project->id,

The problem I've run into is that instead of a hard delete, I'm using a soft delete to remove them from the database, meaning that, for example, 'Test' can only be used as the name once, even after it's been deleted.

How can I make it check that it is unique for that project among the items that are not soft deleted?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

57.0k users

...