自定义表单验证类的 $fail 该怎么响应
1. 运行环境
1). 当前使用的 Laravel 版本?
laravel 10.11
2. 问题描述?
自定义了一个验证类,用于验证选择的商品SKU能不能下单
namespace App\Rules;
use App\Models\Product\Product;
use App\Models\Product\Sku\ProductAttrItem;
use App\Services\Common\HashIdService;
use Closure;
use Illuminate\Contracts\Validation\ValidationRule;
class ProductSkuEnable implements ValidationRule
{
public function validate(string $attribute, mixed $value, Closure $fail): void
{
$sku = ProductAttrItem::query()
->whereHashId($value)
->where('product_id', app(HashIdService::class)->decode(request()->get('product_id')))
->first();
if (is_null($sku)) {
$fail('产品属性已失效,请刷新页面重试');
}
if ($sku->stock < request()->get('quantity')) {
$fail('库存不足');
}
}
}
测试发现,当 $sku
是 null 的时候,仍然会判断第二个 if,接着报错 Attempt to read property \"stock\" on null
如果是把这段代码写在 Request 类中闭包验证,可以通过 return $fail(...)
解决这个问题,但是在 Rule 类中 validate
方法是抽象类 ValidationRule
的接口,并且是被定义得空返回值,不能加 return
所以,是我这个验证类写的有问题吗
你可以在
$fail('产品属性已失效,请刷新页面重试');
下一行加return;