phpmysqllaravellaravel-controllerlaravel-models

Cant return $couponDetails->couponName; value in laravel


$couponCode = $request->couponCode;

// Get coupon details by coupon code
$coupon = Coupon::where('couponCode', $couponCode)
    ->get()
    ->first();

$couponDetails = response()->json($coupon);

return $couponDetails->couponName;

That returns as:

Undefined property: Illuminate\Http\JsonResponse::$couponName (500 Internal Server Error)

I am tring to get couponName value from couponDetails


Solution

  • The error you're getting is because property you're trying to access doesn't exist for the class Illuminate\Http\JsonResponse.

    You have two ways to avoid this:

    1. Either return:

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

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