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

farshadf's avatar

change api output from object to array

i have an api that returns an object as wrapper data in result like below :

{
data: {
totalSalesPrice: 0,
totalDiscount: 0,
finalPrice: 0
}
}

but i want it to be an array like below :

{
data: [
totalSalesPrice: 0,
totalDiscount: 0,
finalPrice: 0
]
}

or maybe even like below :

{
data: [ 
{
totalSalesPrice: 0,
totalDiscount: 0,
finalPrice: 0
}
]
}

how can i achive that ?? and here is my method :

 public function getPriceDetails($bookingId)
    {
        $booking = AccommodationBooking::where('id', $bookingId)->with('accommodationRoom')->first();
        $roomsOfBook = DB::table('accommodation_booking_accommodation_room')->where('accommodation_booking_id', $bookingId)->get();

        $result = [];
        foreach ($roomsOfBook as $room) {
            $roomPricingHistory = RoomPricingHistory::where('accommodation_room_id', $room->accommodation_room_id)
                ->whereDate('from_date', '<=', $booking->from_date)
                ->whereDate('to_date', '>=', $booking->to_date)
                ->orderBy('created_at', 'desc')
                ->first();
            $result[] = $roomPricingHistory;
        }

        $totalSalesPrice = collect($result)->sum('sales_price');
        $totalDiscount = 0;
        $finalPrice = $totalSalesPrice;

        $result['totalSalesPrice'] = $totalSalesPrice;
        $result['totalDiscount'] = $totalDiscount;
        $result['finalPrice'] = $finalPrice;
        return new RoomDetailResource($result);
    }
0 likes
9 replies
Sinnbeck's avatar

I think this would do it

return RoomDetailResource::collect($result);
Sinnbeck's avatar

Btw, this isn't possible as js does not have named keys in arrays (those would be objects

{
data: [
totalSalesPrice: 0,
totalDiscount: 0,
finalPrice: 0
]
}
Sinnbeck's avatar

Of course it might be better if you said why it's needed as an array. There might be a better solution in js

farshadf's avatar

when i use collect i get this error

message: "Call to undefined method App\Http\Resources\RoomDetailResource::collect()",

and when i use

return RoomDetailResource::collecttion($result);

i get this error :

message: "Call to a member function first() on array",
status_code: 500
farshadf's avatar

i get this error when i use collection for it :

message: "Call to a member function first() on array",
status_code: 500
Sinnbeck's avatar

So where is that error thrown? I don't see any php after your return. In your view perhaps?

farshadf's avatar

idk if i get you right or not but i am using dingo api package and that throws error in browser just like above as i copied for you

Sinnbeck's avatar

Sorry I have never used that. My suggestion is based on laravel api resources. And without knowing what file throws the error I have no suggestions

1 like

Please or to participate in this conversation.