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.
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();
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.
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();
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)
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With