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

Laravel中无法获取$couponDetails->couponName值的问题

Laravel获取优惠券名称报错解决方案

你的问题出在错误地把JsonResponse对象当成模型实例访问属性:

  • response()->json($coupon)返回的是Illuminate\Http\JsonResponse类型的响应对象,不是优惠券模型实例,所以直接调用$couponDetails->couponName会触发"Undefined property"错误。
  • 你需要的couponName字段其实在$coupon这个模型实例里,不需要先转成JsonResponse再去获取。

正确写法示例

$couponCode = $request->couponCode;

// 直接用first()查询,比get()->first()更高效
$coupon = Coupon::where('couponCode', $couponCode)->first();

// 先判断优惠券是否存在,避免空属性访问
if ($coupon) {
    // 直接从模型实例获取couponName,再返回响应
    return response()->json(['couponName' => $coupon->couponName]);
}

// 优惠券不存在时返回错误提示
return response()->json(['error' => '该优惠券不存在'], 404);

额外说明

如果你的需求是返回完整的优惠券信息,但同时要在代码里用到couponName,可以这样写:

$couponCode = $request->couponCode;
$coupon = Coupon::where('couponCode', $couponCode)->first();

if ($coupon) {
    // 先获取字段值做其他逻辑处理
    $couponName = $coupon->couponName;
    // ...这里可以加其他业务代码

    // 最后返回完整的优惠券响应
    return response()->json($coupon);
}

return response()->json(['error' => '该优惠券不存在'], 404);

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.28 17:53:04