I have validation issue when I tried to apply the coupon code. I have to apply on 4 condition
- If I applied the correct coupon from the database then it will be fine.
- If I applied the correct coupon again from the database then it will be show the message 'This Coupon Have Already Used'.
- If I just directly key in button (blank value) it will show the message 'Please Insert The Coupon Code'
- But the problem is what I key in the wrong coupon code, I need to have 'Wrong Coupon Code Entered' message displayed
Below is the controller part for the function:-
public function checkCoupon(Request $res)
{
$code = $res->code;
$check = DB::table('coupons')
->where('coupon_code',$code)
->get();
if(count($check)=="1") {
$user_id = Auth::user()->id;
$check_used = DB::table('used_coupons')
->where('user_id', $user_id)
->where('coupon_id', $check[0]->id)
->count();
if($check_used=="0"){
$used_add = DB::table('used_coupons')
->insert([
'coupon_id' => $check[0]->id,
'user_id' => $user_id
]);
$insert_cart_total = DB::table('cart_total')
->insert([
'cart_total' => Cart::total(),
'discount' => $check[0]->discount,
'user_id' => $user_id,
'gtotal' => Cart::total() - (Cart::total() * $check[0]->discount)/100,
]);
}
else{
?>
<div class="alert alert-warning">This Coupon Have Already Used</div>
<?php
}
}
else if($code==$check){
?>
<div class="alert alert-danger">Wrong Coupon Code Entered</div>
<?php }
else{
?>
<div class="alert alert-danger">Please Insert The Coupon Code </div>
<?php }
}
JS file for apply coupon function button:-
$(document).ready(function(){
$('#coupon_btn').click(function(){
var coupon_id = $('#coupon_id').val();
$.ajax({
url:'{{url('/checkCoupon')}}',
data: 'code=' + coupon_id,
success:function(res){
$('#cartTotal').html(res);
}
})
});
});
View File
<div class="cart-total" >
<h4>Total Amount</h4>
<table>
<tbody>
<tr>
<td>Sub Total</td>
<td>$ <?php echo Cart::subtotal(); ?></td>
</tr>
<tr>
<td>Tax (%)</td>
<td>$ <?php echo Cart::tax(); ?></td>
</tr>
<tr>
<td>Grand Total new</td>
<td>$ <?php echo Cart::total(); ?></td>
</tr>
<tr>
<td>Discount(%) </td>
<td> <?php echo $disnew; ?></td>
</tr>
<tr>
<td>Grand Total (After discount) </td>
<td>$ <?php echo $gtnew; ?></td>
</tr>
</tbody>
</table>
<input type="submit" class="btn update btn-block" style="color: white;font-weight: bold;" value="Continue Shopping">
<a href="<?php echo url('checkout') ?>" class="btn check_out btn-block" style="color: white;font-weight: bold;">Checkout</a>
</div>