Skip to content

Eloquent whereBetween with DatePeriod #58092

@Cellard

Description

@Cellard

Laravel Version

12.*

PHP Version

8.*

Database Driver & Version

No matter

Description

As we all know, whereBetween method may accept CarbonPeriod as $values argument. Lets look inside:

    public function whereBetween($column, iterable $values, $boolean = 'and', $not = false)
    {
        $type = 'between';

        if ($values instanceof CarbonPeriod) {
            $values = [$values->getStartDate(), $values->getEndDate()];
        }

        $this->wheres[] = compact('type', 'column', 'values', 'boolean', 'not');

        $this->addBinding(array_slice($this->cleanBindings(Arr::flatten($values)), 0, 2), 'where');

        return $this;
    }

But CarbonPeriod may not have end date! We can construct DatePeriod two ways: passing end-date or passing number of intervals:

$period1 = new \DatePeriod(now(), new \DateInterval('P2M'), now()->addMonths(2));
$period2 = new \DatePeriod(now(), new \DateInterval('P2M'), 2);

$period1 has end-date, but $period2 hasn't.

So I think that in such case method should calculate end-date itself.

Next problem is how between works. Mysql documentation says that between is equivalent to the expression (min <= expr AND expr <= max). Now look at DatePeriod documentation. The fourth argument is an $options, it may accept DatePeriod::EXCLUDE_START_DATE and DatePeriod::INCLUDE_END_DATE.

If DatePeriod excludes start-date, the query should be (min < expr AND expr <= max).
If DatePeriod excludes end-date, the query should be (min <= expr AND expr < max).
If DatePeriod excludes both dates, the query should be (min < expr AND expr < max).

So at the moment Eloquent is not absolutely correct.

And the last but not the least: why this method accepts CarbonPeriod and not accepts base DatePeriod?

I think, that whereBetween

  • should accept DatePeriod
  • should evaluate end-date when required
  • should respect EXCLUDE_START_DATE and INCLUDE_END_DATE options

Steps To Reproduce

No steps required

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions