Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

alaa91's avatar

Laravel add new properties to returned API resource object does not work

I have below Laravel controller methods, I need to customize the returned result, but I have problem as below:

public function getCart(CartProductsRequest $request) { try { $carts = json_decode($request->cart); $products = []; $total = 0; $allCurrency = ""; foreach ($carts as $key => $cart) {

            $product = new  ProductResource(Product::findOrFail($cart->productId));

            $total += $product->finalPrice * $cart->quantity;
            $product->qty = $cart->quantity;
            $product->inStock = $product->inStock();
            $product->totalPrice =  $cart->quantity *  $product->finalPrice;
            $products[] = $product;
            $allCurrency = $product->currency->symbol;
        }

        $cart = ['products' => $products, 'total' => round($total, 2), 'currency' => $allCurrency];

        return JsonResponse::respondSuccess(trans(JsonResponse::MSG_SUCCESS), $cart);
    } catch (\Exception $e) {
        return JsonResponse::respondError($e->getMessage());
    }
}

The result (products) does not contain the new added probertites like qty , I don't know way,

The API resource is (the fields returned):

public function toArray($request) { return [ '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 result is :

{ "result": "success", "content": { "products": [ { "id": 1, "nameEn": "Device 1", "nameAr": "\u062c\u0647\u0627\u0632 1", "slug": "device-1", "details": "Veniam quis accusamus est ea ad ipsa hic. Distinctio assumenda quibusdam magnam nobis aut aliquam nesciunt. Quia unde sapiente maiores temporibus rerum eum. Porro debitis est error quia.", "currency": { "id": 92, "nameAr": "\u0627\u0644\u0644\u064a\u0631\u0629 \u0627\u0644\u062a\u0631\u0643\u064a\u0629", "nameEn": "Turkish Lira", "code": "TRY", "symbol": "TL", "image": null, "status": 1, "isDefault": 1, "createdAt": null, "updatedAt": null }, "offer": { "id": 1, "nameAr": "offer 1", "nameEn": "offer 1", "details": null, "image": null, "status": 1, "discount": "20.00", "addedBy": 1, "updatedBy": null, "startDate": "2021-08-05 08:29:35", "endDate": null, "createdAt": "2021-08-05T08:29:35.000000Z", "updatedAt": "2021-08-05T08:29:35.000000Z", "pivot": { "productId": 1, "offerId": 1 } }, "brand": { "id": 7, "nameAr": "Kasandra Volkman", "nameEn": "Nathanial Larson", "photo": null, "createdAt": "2021-08-05T08:21:34.000000Z", "updatedAt": "2021-08-05T08:29:34.000000Z" }, "category": { "id": 6, "nameAr": "Miss Verna Breitenberg V", "nameEn": "Laurel Wehner IV", "details": "Dolor debitis itaque maiores sed nihil magnam. Illo molestiae quas sed nihil possimus ut. Non qui enim possimus officia quaerat quod voluptate.", "image": "111628152906.jpg", "status": 1, "slug": "laurel-wehner-iv", "lft": 0, "rgt": 0, "parentId": null }, "specifications": [ { "id": 1, "nameEn": "Vance Miller", "nameAr": "Dr. Wellington Jones", "value": "test", "image": null, "createdAt": "2021-08-05T07:53:35.000000Z", "updatedAt": "2021-08-05T08:29:35.000000Z" } ], "merchant": { "id": 2, "name": "merchant", "email": "[email protected]", "phone": "1111", "firstName": "merchant", "lastName": "merchant", "cityId": 1, "street": null, "buildNumber": null, "houseNumber": null, "status": 1, "emailVerifiedAt": "2021-08-05T08:29:34.000000Z", "roleId": 2, "profilePhotoPath": null, "createdBy": null, "updatedBy": null, "currencyId": null, "createdAt": "2021-08-05T08:29:34.000000Z", "updatedAt": "2021-08-05T08:29:34.000000Z", "deletedAt": null, "profilePhotoUrl": "https://ui-avatars.com/api/?name=merchant&color=7F9CF5&background=EBF4FF" }, "images": [ { "id": 12, "name": "/images/products/1_1.png", "orderingShow": 1, "createdAt": "2021-08-05T08:39:10.000000Z", "updatedAt": "2021-08-05T08:39:10.000000Z" }, { "id": 13, "name": "/images/products/1_2.png", "orderingShow": 2, "createdAt": "2021-08-05T08:39:10.000000Z", "updatedAt": "2021-08-05T08:39:10.000000Z" }, { "id": 14, "name": "/images/products/1_3.png", "orderingShow": 3, "createdAt": "2021-08-05T08:39:10.000000Z", "updatedAt": "2021-08-05T08:39:10.000000Z" }, { "id": 15, "name": "/images/products/1_4.png", "orderingShow": 4, "createdAt": "2021-08-05T08:39:10.000000Z", "updatedAt": "2021-08-05T08:39:10.000000Z" }, { "id": 16, "name": "/images/products/1_5.png", "orderingShow": 5, "createdAt": "2021-08-05T08:39:10.000000Z", "updatedAt": "2021-08-05T08:39:10.000000Z" }, { "id": 17, "name": "/images/products/1_6.png", "orderingShow": 6, "createdAt": "2021-08-05T08:39:10.000000Z", "updatedAt": "2021-08-05T08:39:10.000000Z" }, { "id": 18, "name": "/images/products/1_7.png", "orderingShow": 7, "createdAt": "2021-08-05T08:39:10.000000Z", "updatedAt": "2021-08-05T08:39:10.000000Z" }, { "id": 19, "name": "/images/products/1_8.png", "orderingShow": 8, "createdAt": "2021-08-05T08:39:10.000000Z", "updatedAt": "2021-08-05T08:39:10.000000Z" } ], "price": "100.00", "finalPrice": 80, "quantity": 20, "inStock": true, "status": 1, "createdAt": "2021-08-05T08:21:35.000000Z", "updatedAt": "2021-08-05T08:42:43.000000Z" } ], "total": 0, "currency": "TL" }, "message": "responses.msg_success", "status": 200 }

Can you help me please to determine the problem?? (I need the qty in the result) Or if there is another way to map the result

0 likes
12 replies
SilenceBringer's avatar

@alaa91 you are trying to set attributes on Resource, not Product

			$product =Product::findOrFail($cart->productId);

            $total += $product->finalPrice * $cart->quantity;
            $product->qty = $cart->quantity;
            $product->inStock = $product->inStock();
            $product->totalPrice =  $cart->quantity *  $product->finalPrice;
            $products[] =  new  ProductResource($product);
alaa91's avatar

yes it is a new attribute ,i want to add it to each product. therefore my code was :

$product = new ProductResource(Product::findOrFail($cart->productId));

        $total += $product->finalPrice * $cart->quantity;
        $product->qty = $cart->quantity;
        $product->inStock = $product->inStock();
        $product->totalPrice =  $cart->quantity *  $product->finalPrice;
        $products[] = $product;

@silencebringer

SilenceBringer's avatar

@alaa91 first of all - format your code

where you return qty in resource???????

	public function toArray($request)
    {
        return [
            'id' => $this->id,
			'qty' => $this->qty, // <--- just return it!
            '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,
        ];
    }
SilenceBringer's avatar
Level 55

@alaa91

			$product =Product::findOrFail($cart->productId);

            $total += $product->finalPrice * $cart->quantity;
            $product->qty = $cart->quantity; // <- right here you add this attribute to the product
            $product->inStock = $product->inStock();
            $product->totalPrice =  $cart->quantity *  $product->finalPrice;
            $products[] =  new  ProductResource($product);

Pay attention! Add qty before wrapping product into ProductResource

	public function toArray($request)
    {
        return [
            'id' => $this->id,
			'qty' => $this->qty, // <--- right here you output this attribute
            '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,
        ];
    }
alaa91's avatar

Thank you dear, it returned :), i just have another problem: the $product->finalPrice it returned 0 and it should not.

in this $product->totalPrice = $cart->quantity * $product->finalPrice; but it returned truly in the response. @silencebringer

SilenceBringer's avatar

@alaa91 ah-ha, really? maybe just return it in resource too? =)

	public function toArray($request)
    {
        return [
            'id' => $this->id,
			'qty' => $this->qty,
			'totalPrice' => $this->totalPrice, // <--- really, here you can add everything you need to return
            '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,
        ];
    }

or possible wrong attribute name?

$product->totalPrice = $cart->quantity * $product->finalPrice;

you set totalPrice, not finalPrice

really your final price has some dependencies. Close this conversation and start another one, as far as it's out of scope of current conversation

SilenceBringer's avatar

@alaa91 ok, step by step

public function toArray($request)
    {
dd(!!$this->offer->first(), $this->price, $this->offer->first()->discount);
        return [
            'id' => $this->id,
			'qty' => $this->qty,
			'totalPrice' => $this->totalPrice, // <--- really, here you can add everything you need to return
            '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,
        ];
    }

Show me dump results

Please or to participate in this conversation.