如何在拉拉维尔中为产品仅应用一次促销代码



我只需要为一个产品应用一次促销代码,当我对同一产品应用相同的代码时,它不应该被应用。

在下面找到代码:

public function apply_promo(Request $request)
{
$name = $request->input();
$code=$name['code'];
$code_flags=0;
$p_id='';
$discount_value=0;
$discount_type='';
$Object = new Promotion();
$response = $Object->GetPromotion();
//print_r($response);exit;
foreach($response['promotions']['promotion'] as $value)
{
if($value['code']==$code)
{
$code_flags=1;
$p_id=$value['requires'];
$discount_value=$value['value'];
$discount_type=$value['type'];
}
}
if($code_flags==1)
{
$p_id_array=explode(',',$p_id);
$flags=0;
$data=json_encode(Cart::content());
$cartdata=json_decode($data);
//echo "<pre>";print_r($cartdata);exit;
foreach($cartdata as $key => $value)
{
if($value->options->package != 'domain')
{   
if(in_array($value->options->gid,$p_id_array))  
{
$flags=0;
$price=$value->price;
if($discount_type=='Percentage')
{
$discount_p=(($price*$discount_value)/100);
$price=$price-$discount_p;
$value->options->discount_code = $code;
$value->options->discount_price = $discount_p;
$value->options->discount_percentage = $discount_value;
Cart::update($value->rowId, ['price' => $price]);
}
}
}

}
if($flags==0)
{
session()->put('promo_code', $code);
Session::flash('message');
return redirect('cart?success');
}
}
else{
session()->put('promo_code', '');
Session::flash('message_error');
return redirect('cart?error');

}

}

我已经尝试使用上面的代码,但是这里的代码在我提交代码时被应用了很多次。请向我建议解决此问题的解决方案。

你可以把已经使用的促销活动和他们的产品放在表上,比如说我们把它命名product_promotions( promo_id , product_id )。 然后在product模型中创建称为promocodes(many to many)的关系

public function promocodes(){
return $this->belongsToMany(Promo::class)->withPivot(['promo_id']);
}

此关系将返回此产品使用的所有促销,因此我们现在能够使用此代码检查它之前是否使用过促销

$product->promocodes()->where('promo_id' , $your_promo_code_id)->exists();

最新更新