-2
$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

matiaslauriti
  • 7,065
  • 4
  • 31
  • 43
  • Start by looking at what $coupon is `dd($coupon);` and showing us. You have to start your debugging before coming here – RiggsFolly Mar 09 '23 at 18:33
  • Also if you are getting an error, please show us that error as a seperate line in your question and EXACTLY as it was give to you, no summarising – RiggsFolly Mar 09 '23 at 18:34
  • I think `$coupon->couponName` should return the object. – Sachin Bahukhandi Mar 09 '23 at 18:35
  • `$couponDetails` is a `JsonResponse`, not the coupon, so it won't be what you think it is. Remove `$couponDetails = response()->json($coupon);` and return `$coupon->couponName`. Also, `->get()->first()` is unnecessary, because that's returning a collection of probably a single item, then grabbing the first time. Just use `->first()` – aynber Mar 09 '23 at 18:40

2 Answers2

0

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;
    
matiaslauriti
  • 7,065
  • 4
  • 31
  • 43
Sachin Bahukhandi
  • 2,378
  • 20
  • 29
0

As another user already stated but not with more code, I will show you how to do it:

// Store coupon code on variable (no need to)
$couponCode = $request->couponCode;

// Get coupon details by coupon code (directly use first() so you get the model in one run)
$coupon = Coupon::where('couponCode', $couponCode)->first();

// Here you can either return the model as a JSON response (and in the view you do `$data->couponName`
response()->json(['data' => $coupon]);

// Or you directly return the coupon name
return $couponDetails->couponName;
matiaslauriti
  • 7,065
  • 4
  • 31
  • 43