Home / Snippets / How to Query Between 2 Dates in Laravel Eloquent
How to Query Between 2 Dates in Laravel Eloquent cover

How to Query Between 2 Dates in Laravel Eloquent

275

3 years ago

0 comments

To query a record between 2 dates in Laravel you can make use of the whereBetween method available to all ELoquent ORM. In this code snippet, we'll be showing you the use of the Carbon instance.
<?php

use App\Model\Post;

$from = date('2021-10-10');
$to = date('2021-10-20');

// Get all posts from 10th of October to 20th of October
Post::query()
    ->whereBetween('created_at', [$from, $to])
    ->get();

Using Carbon Instance


Besides using the "date()" method you can also use the Carbon instance.
<?php

use Carbon\Carbon;
use App\Model\Post;

$from = Carbon::parse('2021-10-10');
$to = Carbon::parse('2021-10-20');

// Get all posts from 10th of October to 20th of October
Post::query()
    ->whereBetween('created_at', [$from, $to])
    ->get();

Getting Posts for Past 3 Months


You can also get the records for the past x months using the method mentioned above.
<?php // get posts record for the past 3 months

$posts = Posts::query()
    ->whereBetween(now(), now()->subMonths(3))
    ->get();
Do note that "now()" is just a handy helper method for the "Carbon::now()" function.
notion avatar

Alaz

Week-end developer currently experimenting with web, mobile, and all things programming.

Topics:

Frontend

Resource

Average

Average

Support Us

If you like our tutorial, support us by being our Patreon or buy us some coffee ☕️

Welcome to PostSrc V3

PostSrc Dark Logo

You have to login to favorite this