manu123's avatar

laravel eloquent: whereDate not found record included into the period

Problem: I would like to select the period, for example: August 25 to August 31 and I want to have ALL the records that include those dates, example: from 25 to 31 from 23 to 31 from 23 January to 30 September from 31 August to 2 September etc all those who "cross" from 25 to 31 August

I have a table with two date fields:

reservation_begin
booking_end

I want to know the reservations that occupy me from August 25th to August 31st.

In the select query I have:

Booking::select ('id', ''name', reservation_begin', 'reservation_end') ->whereDate('reservation_begin', '>=', $startDate) ->whereDate('reservation_end', '<=', $endDate) ->get();

I will NOT find the record in the database if: $startDate = '2021-08-25'; $endDate = '2021-09-01' (from 25 August to 1 September).

I want to have reservations that include the period from August 25 to August 31, and the reservation that goes from August 25 to September 1 still includes that period, how can I get it out?

Thank you for your help

0 likes
1 reply
MichalOravec's avatar
Level 75

Maybe something like this

$bookings = Booking::select('id', 'name', 'reservation_begin', 'reservation_end')
    ->where(function ($query) use ($startDate, $endDate) {
        $query->whereBetween('reservation_begin', [$startDate, $endDate])
              ->orWhereBetween('reservation_end', [$startDate, $endDate])
              ->orWhere(function($query) use ($startDate, $endDate) {
                    $query->whereDate('reservation_begin', '<=', $startDate)
                          ->whereDate('reservation_end', '>=', $endDate);
                });
    })->get();

Please or to participate in this conversation.