Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get data of previous week in Laravel 5.1?

I want to get data inserted in previous week in Laravel 5.1. Currently I am using following query:

$AgoDate=\Carbon\Carbon::now()->subWeek()->format('Y-m-d');  // returns 2016-02-03
$NowDate=\Carbon\Carbon::now()->format('Y-m-d');  // returns 2016-02-10
$query->whereBetween('created_on', array($AgoDate,$NowDate));

This returns last 7 days data, but I need last week's data, which means it should return data from 31st Jan to 6th Feb, i.e. the previous week.

Note: in my case Week starts from Sunday and ends on Saturday.

like image 757
Amrinder Singh Avatar asked Feb 10 '16 05:02

Amrinder Singh


1 Answers

EDIT: adjusting to OP's question

For ago date use

$currentDate = \Carbon\Carbon::now();
$agoDate = $currentDate->subDays($currentDate->dayOfWeek)->subWeek();// gives 2016-01-31

Similarly you can get your nowDate

$currentDate = \Carbon\Carbon::now();
$nowDate = $currentDate->subDays($currentDate->dayOfWeek + 1); // gives 2016-02-06

to adjust the weekstart(sunday/monday) I think you can add/subtract some days to dayOfWeek e.g $currentDate->subDays($currentDate->dayOfWeek + 1 /* or -1 */);

EDIT : as mentioned in the comments you can also use startOfWeek() method instead of subDays() if it works directly for you.

like image 67
codisfy Avatar answered Sep 27 '22 17:09

codisfy