如何通过忽略 Laravel 中的软删除项来对数据库记录的给定输入进行唯一验证?任何人都可以回答我吗?
2 回答
您可以向存在规则添加一个条件,基本上像这样过滤结果deleted_at == NULL
:
$request->validate([
'foo' => 'exists:table,column,deleted_at,NULL',
]);
泰勒本人在Github 问题上回答了这个问题。
您还可以创建自定义验证规则:
<?php
namespace App\Rules;
use Illuminate\Contracts\Validation\Rule;
class UniqueWithoutSoftDelete implements Rule
{
/**
* Determine if the validation rule passes.
*
* @param string $attribute
* @param mixed $value
* @return bool
*/
public function passes($attribute, $value)
{
// Your logic goes here
// Return true to pass the validation
// ie: return Model::where($attribute, $value)->exists();
}
/**
* Get the validation error message.
*
* @return string
*/
public function message()
{
return 'The :attribute must be unique.';
}
}
要在您的控制器中实现它,请添加:
use App\Rules\UniqueWithoutSoftDelete;
在您的控制器方法中:
$request->validate([
'foo' => ['required', new UniqueWithoutSoftDelete],
]);
希望这对您有所帮助。
我用另一种方式解决了它......在请求类中,编写以下代码:public function rules()
{
switch ( $this->method() ){
case 'POST':
return [
'currency_id' => ['required', Rule::unique('company_currencies')->where(function ($query) {
$query->where('deleted_at', Null);
})
],
];
break;
}
并在类文件的顶部use Illuminate\Validation\Rule;