Home > Backend Development > PHP Tutorial > How to Retrieve Records Within a Specific Date Range Using Laravel's Eloquent ORM?

How to Retrieve Records Within a Specific Date Range Using Laravel's Eloquent ORM?

Mary-Kate Olsen
Release: 2024-12-08 07:49:13
Original
653 people have browsed it

How to Retrieve Records Within a Specific Date Range Using Laravel's Eloquent ORM?

Retrieving Records Based on a Date Range Using Laravel

To retrieve records that fall within a specified date range, Laravel's Eloquent ORM provides the whereBetween method. This method allows you to specify a column name and an array of two dates, representing the start and end points of the desired range.

$from = date('2018-01-01');
$to = date('2018-05-02');

Reservation::whereBetween('reservation_from', [$from, $to])
    ->get();
Copy after login

This query will retrieve all reservations where the reservation_from column value falls between January 1st, 2018 and May 2nd, 2018.

Dynamic Range Parameters

You can also dynamically define the start and end dates of the range using Carbon's between method:

Reservation::all()
    ->filter(function($item) {
        if (Carbon::now()->between($item->from, $item->to)) {
            return $item;
        }
    });
Copy after login

Additional Queries

  • whereOrBetween: Specifies an additional date range condition.
  • whereNotBetween: Excludes a specific date interval.

Example:

Reservation::whereBetween('reservation_from', [$from1, $to1])
    ->orWhereBetween('reservation_to', [$from2, $to2])
    ->whereNotBetween('reservation_to', [$from3, $to3])
    ->get();
Copy after login

Other Where Clauses

For further flexibility, Laravel offers additional WHERE clauses, including:

  • whereIn
  • whereNotIn
  • whereNull
  • whereNotNull
  • whereDate
  • whereMonth
  • whereDay
  • whereYear
  • whereTime
  • whereColumn
  • whereExists
  • whereRaw

The above is the detailed content of How to Retrieve Records Within a Specific Date Range Using Laravel's Eloquent ORM?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template