You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Laravel Ajax加入购物车报500内部服务器错误,请求排查

Laravel加入购物车500错误排查

问题描述

开发Laravel电商功能时,点击加入购物车按钮触发500内部服务器错误,无法实现「检查商品是否已在购物车并给出对应提示」的预期功能。

页面视图代码

@extends('layouts.frontend.frontend')
@section('title')
Distinctly Mine - {{$products->name}}
@endsection
@section('content')

<div class="py-3 mb-4 shadow-sm babyblue border-top">
    <div class="container">
        <h6 class="mb-0">Collections / {{$products->category->name}} / {{$products->name}}</h6>
    </div>
</div>

<div class="container">
    <div class="card-shadow shadow-sm product_data">
        <div class="card-body">
            <div class="row">
                <div class="col-md-4 border-right">
                <div class="img-hover-zoom img-hover-zoom--xyz card-img-top">
                <img src="{{ asset('backend/uploads/products/'.$products->image) }}" class="w-100 h-100" alt="{{$products->name}}">
            </div>
            </div>
            <div class="col-md-8">
            <h2 class="mb-0">{{ $products->name}}</h2> 

                <hr>
                <label for="" class="me-3">Price: ${{$products->original_price}}</label>
                <p class="mt-3">{!! $products->small_description !!}</p>
                <hr>
                @if($products->qty > 0)
                <label for="" class="badge bg-success text-dark fw-bold">In Stock</label>
                @else 
                <label for="" class="badge bg-danger text-dark fw-bold">Out of Stock</label>
                @endif

                <div class="row mt-2">
                    <div class="col-md-2">
                        <input type="hidden" value="{{$products->id}}" class="prod_id">
                        <label for="Quantity">Quantity</label>
                        <div class="input-group text-center mb-3" style="width:130px">
                            <button type="button" class="input-group-text decrement-btn">-</button>
                            <input type="text" name="quantity" value="1" class="form-control qty-input" />
                            <button type="button" class="input-group-text increment-btn">+</button>
                        </div>
                    </div>
                    <div class="col-md-10">
                        <br />
                        <button type="button" class="btn btn-warning text-dark fw-bold ms-3 float-start"><i class=" me-1 fa fa-heart text-danger me-1"></i>Add To Wishlist</button>
                        <button type="button" class="btn btn-success ms-3 float-start text-dark fw-bold addToCartBtn"><i class="me-1 fa fa-shopping-cart text-dark me-1"></i>Add to Cart</button>
                    </div>

                    <hr>
                    <h2>Description</h2>
                    {{$products->description}}
                </div>

            </div>
        </div>
    </div>
</div>

@endsection

@section('scripts')
<script>
    $(document).ready(function (){
        $('.addToCartBtn').click(function (e){
            e.preventDefault();
            var product_id = $(this).closest('.product_data').find('.prod_id').val();
            var product_qty = $(this).closest('.product_data').find('.qty-input').val();
            
            $.ajaxSetup({
                headers: {
                    'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
                }
            });

            $.ajax({
                method: "POST",
                url: "/add-to-cart",
                data: {
                    'product_id': product_id,
                    'product_qty': product_qty,
                },
                dataType: "json",
                success: function (response){
                    alert(response.status);
                },
                error: function(){
                    alert('请求异常,请查看服务器日志');
                }
            });
        });

        $('.increment-btn').click(function (e){
            e.preventDefault();
            var inc_value = $('.qty-input').val();
            var value = parseInt(inc_value,10);
            value = isNaN(value) ? 0 :value;
            if(value < 10)
            {
                value++;
                $('.qty-input').val(value);
            }
        });

        $('.decrement-btn').click(function (e){
            e.preventDefault();
            var dec_value = $('.qty-input').val();
            var value = parseInt(dec_value,10);
            value = isNaN(value) ? 0 :value;
            if(value > 1)
            {
                value--;
                $('.qty-input').val(value);
            }
        }); 
    });
</script>
@endsection

路由代码

Route::middleware(['auth'])->group(function (){
    Route::post('/add-to-cart',[CartController::class,'addProduct']);
});

控制器代码(修复后)

<?php

namespace App\Http\Controllers\Frontend;

use App\Models\Product;
use App\Models\Cart;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use Illuminate\Support\Facades\Auth;

class CartController extends Controller
{
    public function addProduct(Request $request)
    {
        $product_id = $request->input('product_id');
        $product_qty = $request->input('product_qty');
        
        if(Auth::check())
        {
            $prod_check = Product::where('id',$product_id)->first();
            
            if($prod_check)
            {
                if(Cart::where('prod_id',$product_id)->where('user_id',Auth::id())->exists())
                {
                    return response()->json(['status' => $prod_check->name . " 已在购物车中"]);
                }
                else
                {
                    $cartItem = new Cart();
                    $cartItem->prod_id = $product_id;
                    $cartItem->user_id = Auth::id();
                    $cartItem->prod_qty = $product_qty;
                    $cartItem->save();
                    return response()->json(['status' => $prod_check->name . " 已添加到购物车"]);
                }
            }
            else
            {
                return response()->json(['status' => "商品不存在"]);
            }
        }
        else
        {
            return response()->json(['status'=> "请登录后操作"]);
        }
    }
}

错误排查及修复点

  • Cart模型未引入:原控制器未导入Cart模型命名空间,导致类找不到,需添加use App\Models\Cart;(模型路径根据实际项目调整)。
  • AJAX dataType错误:前端AJAX配置中dataType写为"dataType",需改为"json"以正确解析返回数据。
  • 缺少错误处理:前端AJAX添加error回调,方便捕获请求异常。
  • 空值场景未处理:补充商品不存在时的返回逻辑,避免空指针报错。
  • HTML实体转义问题:原视图代码中的&quot;替换为正常双引号,避免JS/HTML解析错误。

内容的提问来源于stack exchange,提问作者ToddM

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.03 00:52:40