Home > Backend Development > PHP Tutorial > How to Query Data Between Two Dates Using Laravel Eloquent?

How to Query Data Between Two Dates Using Laravel Eloquent?

Linda Hamilton
Release: 2024-12-17 21:09:15
Original
846 people have browsed it

How to Query Data Between Two Dates Using Laravel Eloquent?

How to Query Between Two Dates Using Laravel and Eloquent?

You can use Eloquent's whereBetween method to query between two dates. This method takes an array of two values as its arguments, where the first value is the start date and the second value is the end date. For example:

<?php

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

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

This query will select all reservations where the reservation_from column is between the start date and the end date.

Dynamic Date Range

You can also add the date range dynamically using the filter method. For example:

<?php

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

Multiple Conditions

You can use multiple conditions by chaining the where methods. For example:

<?php

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

Other Useful Where Clauses

Laravel Eloquent provides other useful where clauses, including:

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

For more information, refer to the Laravel documentation on [Where Clauses](https://laravel.com/docs/eloquent/queries) and [whereBetween](https://laravel.com/docs/eloquent/queries#where-clauses).

The above is the detailed content of How to Query Data Between Two Dates Using Laravel Eloquent?. 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