Kanu Patel
Kanu Patel

Reputation: 23

SQL BETWEEN Operator in Laravel

SELECT * FROM mytable WHERE created_date 
    BETWEEN CURDATE() - INTERVAL 90 DAY AND CURDATE();

How can I write this query in Laravel?

Upvotes: 0

Views: 142

Answers (3)

Girdharilal Pandey
Girdharilal Pandey

Reputation: 94

I think this will solve your problem:

use Carbon\Carbon;

$now = Carbon::now();
$prev = Carbon::now()->subDays(90);

DB::table('mytable')->where(function ($query) use ($now,$prev) {
    $query->whereBetween('created_date', [$prev, $now]);
})->get();

Upvotes: 1

Babak Asadzadeh
Babak Asadzadeh

Reputation: 1239

Laravel have a good solution for this and it is whereBetween see that here https://laravel.com/docs/5.6/queries

Upvotes: 2

Sahith Vibudhi
Sahith Vibudhi

Reputation: 5205

The following query gives you records that has date between now and date 90 days back:

$now = date('Y-m-d'); // now
$old = date('Y-m-d', strtotime('-90 days')); // 90 days back
$records = DB::table('mytable')->where('created_date', '>=', $old)
                       ->where('created_date', '<=', $now)
                       ->get();

You should read Laravel Docs: https://laravel.com/docs/5.1/queries#where-clauses

Hope it helps.

Upvotes: 0

Related Questions