Home > database >  Laravel search across multiple date ranges
Laravel search across multiple date ranges

Time:01-31

id listing_id start_date end_date
1 1 2023-01-20 2023-01-25
2 1 2023-02-26 2023-02-10
3 1 2023-02-11 2023-02-20
4 1 2023-02-21 2023-02-27
$listings->whereHas(
    'availabilityCalendar',
    function ($query) use ($start_date, $end_date) {
        $query->where('start_date', '>=', $start_date)
            ->where('end_date', '<=', $end_date);
    })
}

Fetch data according to start_date = 2023-01-23 / end_date = 2023-02-20 I sent by frontend. The start_date and end_date values I sent are among the values in the records I wrote above.

If I sent start_date = 2023-01-01 / end_date = 2023-02-20 they wouldn't be included. Or if I had submitted the dates start_date = 2023-01-23 / end_date = 2024-01-01 they would still not be included.

But if I sent the dates start_date = 2023-02-01 / end_date = 2023-02-15 it would have been met.

Can you help with this?

CodePudding user response:

You should make sure your query are casted as date.

You can do some thing like

$startDate = Carbon::createFromFormat('Y-m-d', $start_date);
$endDate = Carbon::createFromFormat('Y-m-d',  $end_date);

$query->whereDate('start_date', '>=', $startDate )
    ->whereDate('end_date', '<=', $endDate );

or

$query->where(DB::raw('DATE(start_date)'), '>=', $startDate )
    ->where(DB::raw('DATE(end_date)'), '<=', $endDate );
  • Related