Search code examples
laraveleloquentdate-rangephp-carbon

Laravel: How can I add an individual price from a table for each date within a given date range?


I try to calculate the room rates dynamically. My table of room rates has currently three fields:

id | room_rate | starting_from | ending_in
 1 |        60 | 2019-12-01    | 2019-12-20
 2 |        80 | 2019-12-21    | 2020-01-04

If the user has a check-in and check-out date, I would like to check the price for each day.

My public function to get the indivudal nights looks like this:

$booking_date_start[] = $request->input('booking_date_start');
$booking_date_end[] = $request->input('booking_date_end');

$booking_total = array();

foreach(array_combine($booking_date_start, $booking_date_end) as $check_in => $check_out) {
    $check_in = new Carbon($check_in);
    $check_out = new Carbon($check_out);
    while ($check_in->lte($check_out)) {
        $booking_total[] = $check_in->toDateString();
        $check_in->addDay();
    }
    array_pop($booking_total);
}

return response()->json($booking_total);

Output of my function (check-in: 2019-12-20; check-out: 2019-12-23):

["2019-12-20","2019-12-21","2019-12-22"]

How can I parse the table of room rates and add the indivudal price for each date?

I need something like this:

["2019-12-20, 60","2019-12-21, 80","2019-12-22, 80"]

Thanks!


Solution

  • I solved this. For those who are interested in.

    First I refactored my table of room rates. I use for each date a separate entry in my table with the individual price (no date ranges anymore).

    Second I filtered my table of room rates. I combined the $booking_total value with my database query (whereIn method) and decode the result in a JSON format.