Reputation: 2000
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);
}
Upvotes: 0
Views: 185
Reputation: 89
Since you are returning a resource, laravel believes you want to return just one resource.
However, if you want an array of rooms, you can return a resource collection.
return RoomDetailResource::collection($result);
This will be formatted as
data: [
{
totalSalesPrice: 0,
totalDiscount: 0,
finalPrice: 0
}
]
}
Upvotes: 1
Reputation: 835
I would like to see how you return the data in the RoomDetailResource. Ideally, to achieve the second result, you could just return a JSON response from your RoomDetailResource of the manner:
return response()->json([
'data' => your_result
], status_code);
Assuming this is our result to output:
$result['totalSalesPrice'] = $totalSalesPrice;
$result['totalDiscount'] = $totalDiscount;
$result['finalPrice'] = $finalPrice;
In this case, you get the output:
{
data: [
{
totalSalesPrice: 0,
totalDiscount: 0,
finalPrice: 0
}
]
}
Here is a sample from my code:
This is my service and returns a collection.
Upvotes: 1