search

Home  >  Q&A  >  body text

The value of $couponDetails->couponName cannot be returned in Laravel

<p><br /></p> <pre class="brush:php;toolbar:false;">$couponCode = $request->couponCode; // Get coupon details through discount code $coupon = Coupon::where('couponCode', $couponCode) ->get() ->first(); $couponDetails = response()->json($coupon); return $couponDetails->couponName; </pre> <p>The return result is as follows:</p> <blockquote> <p>Undefined property: IlluminateHttpJsonResponse::$couponName (500 Internal Server Error)</p> </blockquote> <p>I am trying to get the value of couponName from couponDetails</p>
P粉714890053P粉714890053496 days ago579

reply all(3)I'll reply

  • P粉950128819

    P粉9501288192023-08-21 13:53:36

    As another user already mentioned, but without more code I will show you how to do it:

    // 将优惠券代码存储在变量中(不需要)
    $couponCode = $request->couponCode;
    
    // 通过优惠券代码获取优惠券详情(直接使用first()方法,以便一次性获取模型)
    $coupon = Coupon::where('couponCode', $couponCode)->first();
    
    // 在这里,您可以将模型作为JSON响应返回(在视图中使用`$data->couponName`)
    response()->json(['data' => $coupon]);
    
    // 或者您可以直接返回优惠券名称
    return $couponDetails->couponName;
    

    reply
    0
  • P粉807471604

    P粉8074716042023-08-21 11:54:50

    The error you are getting is because the property you are trying to access does not exist in class Illuminate\Http\JsonResponse.

    You have two ways to avoid this problem:

    1. Or return:

      return $coupon->couponName;
      
    2. Get data from JsonResponse class:

      return $couponDetails->getData()->couponName;
      

    reply
    0
  • Cancelreply