我对我的表单请求进行了自定义验证.当用户输入值并且值也存在时,字段DELETED_AT不为空,则该验证应该起作用.
问题是,即使我输入了不存在的值,Delete_at也是空的.验证仍在起作用.
这就是我所做的
自定义验证:
<?php
namespace App\Rules;
use Closure;
use Illuminate\Contracts\Validation\Rule;
use App\Models\Product;
class SkuDeletedValidationRule implements Rule
{
/**
* Run the validation rule.
*
* @param \Closure(string): \Illuminate\Translation\PotentiallyTranslatedString $fail
*/
public function passes($attribute, $value)
{
// Retrieve the model instance based on the SKU value
$model = Product::where('sku', $value)->first();
// Check if the model exists and its deleted_at is not null
if( $model && $model->deleted_at !== null){
return true;
}
return false;
}
public function message()
{
return 'The :attribute is exists but has been deleted, please restore it.';
}
}
我的表格请求:
use App\Models\Product;
use Illuminate\Foundation\Http\FormRequest;
use Illuminate\Support\Str;
use App\Rules\SkuDeletedValidationRule;
class ProductRequest extends FormRequest
{
/**
* Determine if the user is authorized to make this request.
*/
public function authorize(): bool
{
return auth('cms-admin')->check();
}
/**
* Get the validation rules that apply to the request.
*
* @return array<string, \Illuminate\Contracts\Validation\ValidationRule|array|string>
*/
public function rules(): array
{
return [
'name' => 'required',
'sku' => [new SkuDeletedValidationRule, 'required' . $this->product?->id],
'sku_merchant' => 'nullable|unique:products,sku_merchant,' . $this->product?->id,
'slug' => 'nullable',
'is_publish' => 'required',
'price' => 'required',
'description' => 'required',
'discount' => 'nullable',
'images.*' => 'required',
'category.*' => 'nullable|exists:categories,id',
'supplier_id' => 'required',
'buyer_price' => 'required'
];
}
}
我的控制器:
public function store(ProductRequest $request)
{
$this->productService->create($request->validated());
return redirect(route('admin.product.index'))->with('success', 'product created!');
}
当我输入不存在的值时
在我的自定义验证中需要修复什么才能正常工作?提前谢谢你了.