Posts Learn Components Snippets Categories Tags Tools About
/

How to Query Between 2 Dates in Laravel Eloquent

Learn how to query record between 2 dates in Laravel using eloquent

Created on Oct 26, 2021

254 views

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.

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

)