
Когда я ввожу код скидки и нажимаю кнопку «Применить». Общая цена должна быть изменена, но она не изменилась.
cart.blade.php
Код: Выделить всё
Apply
Код: Выделить всё
function changeDiscount(event, id, cartName = null) {
event.preventDefault();
var discountCode = document.querySelector('input[name="discount_code"]').value;
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': document.head.querySelector('meta[name="csrf-token"]').content,
'Content-Type': 'application/json'
}
});
$.ajax({
type: 'POST',
url: '{{ route('discount.change') }}',
data: JSON.stringify({
id: id,
coupon: discountCode,
_method: 'patch'
}),
success: function (res) {
location.reload();
console.log(res);
},
error: function (error) {
console.error(error);
}
});
}
Код: Выделить всё
Route::patch('/cart/discount/change', [App\Http\Controllers\CartController::class, 'discountChange'])->name('discount.change');
Код: Выделить всё
use App\Services\Cart\Cart;
public function discountChange(Request $request)
{
$data = $request->validate([
'coupon' => 'required',
'id' => 'required',
]);
if(Cart::has($data['id'])) {
Cart::update($data['id'] , [
'coupon' => $data['coupon']
]);
$discountCode = $data['coupon'];
$discount = Discount::query()->where('discount_code', $discountCode)->first();
if ($discount) {
$discountPercent = $discount->discount_percent;
$courses = $discount->courses()->get();
foreach ($courses as $course) {
$course->price = $course->price * (1 - $discountPercent / 100);
}
$price = number_format($course->price);
$totalPriceDiscount = "Discounted price: $price";
return $totalPriceDiscount;
} else {
alert()->error('Promotion Code is invalid.')->showConfirm('ok');
}
return response(['status' => 'success']);
}
return response(['status' => 'error'] , 404);
}
Код: Выделить всё
Подробнее здесь: [url]https://stackoverflow.com/questions/77334732/how-to-change-price-when-i-enter-discount-code[/url]
Мобильная версия