是不是应该加上 `optional ($sku)`?
function ($attribute, $value, $fail) {
if (!$sku = ProductSku::find($value)) {
$fail('该商品不存在');
}
if (!$sku->product->on_sale) {
$fail('该商品未上架');
}
if ($sku->stock === 0) {
$fail('该商品已售完');
}
// 获取当前索引
preg_match('/items\.(\d+)\.sku_id/', $attribute, $m);
$index = $m[1];
// 根据索引找到用户所提交的购买数量
$amount = $this->input('items')[$index]['amount'];
if (is_int($amount) && $amount > $sku->stock) {
$fail('该商品库存不足');
}
},
在这个闭包验证当中, 如果 !$sku = ProductSku::find($value)
为真,那么 $sku
就等于 null
,于是到 $sku->product->on_sale
会报错 Trying to get property of non-object
是不是应该加上 optional($sku)
?
推荐文章: