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

armingdev's avatar

Two dates on 2 fields query

Hello,

I need to write query for following situation:

I have two columns in reservation table, 'checkin' and 'checkout' (dates both). When new reservation is being made, in request that I receive there is two parameters $from and $to (also dates). I need to check if there is existing reservation between this $from and $to dates in my database(between checkin and checkout).

simple: need to check if there is any existing reservation at period that i receive from request.

0 likes
3 replies
tykus's avatar
tykus
Best Answer
Level 104

I have the following query scope which does something similar (begin and end are the column names; while $start and $end are the limits of the proposed new interval):

public function scopeIntersecting($query, $start, $end)
{
    return $query->where(function ($qry) use ($start, $end) {
        $qry->where(function ($q) use ($start, $end) {
            $q->where('begin', '>=', $start)
                ->where('begin', '<', $end);
        })->orWhere(function ($q) use ($start, $end) {
            $q->where('begin', '<=', $start)
                ->where('end', '>', $end);
        })->orWhere(function ($q) use ($start, $end) {
            $q->where('end', '>', $start)
                ->where('end', '<=', $end);
        })->orWhere(function ($q) use ($start, $end) {
            $q->where('begin', '>=', $start)
                ->where('end', '<=', $end);
        });
    });
}

This query covers all of the following scenarios:

    from                                 to
    ╔════════════════════════════════════╗
    ║................S────────────E......║
S──────────────────────────────────────────E
S──────────────E.........................║
    ║...............................S───────────E
    ╚════════════════════════════════════╝
armingdev's avatar

That is what I needed. Thank you both for help.

Please or to participate in this conversation.