Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to check current date is between two dates in laravel 5.4

Tags:

php

mysql

laravel

I have a table

    +---------------------+-----------
    | id | start_date     |  End_date |
    +---------------------+-----------+
    |   1  | 2017-07-07   | 2017-07-31|
    |   2  | 2017-08-01   | 2017-08-31|
    |   3  | 2017-09-01   | 2017-09-10|
    |  
    +------+--------------+-----------+

And I want to select dates between two dates.I have a query

 SELECT * FROM Financial_Year WHERE CURDATE() between `start_date` and `End_date`

I want to convert this query to laravel so i tried this

 $dt = Carbon::now();
 $getmonths= DB::table('Financial_Year')
                    ->whereBetween($dt, ['start_date', 'End_date'])->get();

But i didn't get output.Any help would be appreciated.

like image 562
Shanu k k Avatar asked Jul 10 '17 06:07

Shanu k k


People also ask

How to check if current date is between two dates in laravel?

How can we get data between two dates using query in laravel? Get data between two dates with MySQL Raw Query $startDate = '2022-06-01'; $endDate = '2022-06-30'; Post::whereBetween(DB::raw('DATE(created_at)'), [$startDate, $endDate])->get();

How do I use whereBetween in laravel?

The whereBetween() method is a query builder chained alongside other Laravel query builders used to fetch data from the database. The whereBetween() method queries the database table to fetch rows of records from the database within a range of values.


3 Answers

Here you can use laravel whereRaw() to achieve this.

Just like this

$dt = Carbon::now();
$getmonths= DB::table('Financial_Year')
    ->whereRaw('"'.$dt.'" between `start_date` and `End_date`')
    ->get();
like image 128
Bibhudatta Sahoo Avatar answered Oct 14 '22 01:10

Bibhudatta Sahoo


You can use Carbon native function for this:

http://carbon.nesbot.com/docs/

$first = Carbon::create(2012, 9, 5, 1);
$second = Carbon::create(2012, 9, 5, 5);
var_dump(Carbon::create(2012, 9, 5, 3)->between($first, $second));  // bool(true)
var_dump(Carbon::create(2012, 9, 5, 5)->between($first, $second));  // bool(true)
like image 34
lewis4u Avatar answered Oct 14 '22 01:10

lewis4u


If you want to use only Laravel Query Builder maybe you could try:

$date_start = Carbon::now()->startOfYear();
$date_end = Carbon::now()->endOfYear();

$query = Model::where('created_at', '<=', $date_end)
        ->where('created_at', '>=', $date_start)
        ->get();

In the variables of date_start and date_end you will put the range you want to use. Maybe is during the same month, during the same year or you could use:

$date = Carbon::create(2012, 9, 5, 5);

to determine the date manually.

like image 1
Jorge Peña Avatar answered Oct 14 '22 00:10

Jorge Peña