-1

The resource collection:

public function toArray($request)
    {
        return [
            'test' => 55,
            'id' => $this->id,
            'name_en' => $this->name_en,
            'name_ar' => $this->name_ar,
            'slug' => $this->slug,
            'details' => $this->details,
            'currency' => $this->currency,
            'offer' => $this->offer->first(),
            'brand' => $this->brand,
            'category' => $this->category,
            'specifications' => SpesificationResource::collection($this->specifications),
            'merchant' => $this->merchant,
            'images' => count($this->images) > 0 ? ImageResource::collection($this->images) : asset("/images/default.png"),
            "price" => $this->price,
            "finalPrice" => $this->offer->first() ? $this->price - ($this->price * $this->offer->first()->discount / 100) : $this->price,
            'quantity' => $this->quantity,
            'inStock' => $this->inStock(),
            'status' => $this->status,
            'created_at' => $this->created_at,
            'updated_at' => $this->updated_at,

        ];
    }

The controller:

 public function show($id)
    {
        try {
            $product = new ProductResource(Product::findOrFail($id));
           return $product->test;
          //  return JsonResponse::respondSuccess(trans(JsonResponse::MSG_SUCCESS), $product);
        } catch (\Exception $e) {
            return JsonResponse::respondError($e->getMessage());
        }
    }

when I use the test value inside the controller it's not returned, although it returned when I call it from Postman.

What the problem here?

Alaa Hameed
  • 13
  • 1
  • 5

1 Answers1

0

$product is an instance of ProductResource And of course there is no test property on that class. And it does not implement the magic __get method.

So what you can do is either use $product['test'] cause it implements ArrayAccess or first you can do $product = (new ProductResource(Product::findOrFail($id)))->toArray($request); Then again you can use $product['test'] to get the test value.

Can Vural
  • 2,222
  • 1
  • 28
  • 43