沃梦达 / 编程问答 / php问题 / 正文

使用 laravel 验证检查名称在未删除项目中是否唯一

Check if name is unique among non-deleted items with laravel validation(使用 laravel 验证检查名称在未删除项目中是否唯一)

本文介绍了使用 laravel 验证检查名称在未删除项目中是否唯一的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个简单的表单,它发布到一个控制器,该控制器检查一个项目的名称是否已经用于特定项目.如果是,则返回错误.这是我正在使用的代码:

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,

我遇到的问题是,我没有使用硬删除,而是使用软删除将它们从数据库中删除,这意味着,例如,Test"只能用作名称一次,即使它已被删除.

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?

推荐答案

你可以试试这个:

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

这将确保 versions 表中的 name 是唯一的,如果一条记录被软删除并且具有相同的名称 name 则不会被计算在内, 表示即使存在同名的软删除记录,名称也会被接受.

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.

要在更新时忽略模型,您应该在 name 之后传递 id 来代替第一个 NULL.

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

});

你可以这样使用它:

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

这篇关于使用 laravel 验证检查名称在未删除项目中是否唯一的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!

本文标题为:使用 laravel 验证检查名称在未删除项目中是否唯一