Reputation: 5608
I have the following code to fetch the records :
App\User::orderBy('balance', 'DESC')->limit(3)->get();
How can i get the records for today, Last week and last month ?
I was adding DB::raw('MONTH(created_at)', '=', date('m'))
but had no good !
Upvotes: 0
Views: 6234
Reputation: 1892
You can handle dates really nicely using Carbon, it's built into laravel so here's a few examples how we can make use of it.
use Carbon\Carbon;
Maybe date will equal something like this:
//one day (today)
$date = Carbon::now()->startOfDay;
//one month / 30 days
$date = Carbon::now()->subDays(30)->startOfDay;
App\User::where('field_name', '>=', $date)->orderBy('field_name', 'desc')->limit(3)->get();
You can see the full carbon docs over at http://carbon.nesbot.com/docs/
Good luck!
Upvotes: 5
Reputation: 2325
To do so better to create scopes in your model, example for Last week:
public function scopeLastWeek($query)
{
return $query->where($query->created_at->diffInDays($query->created_at->copy()->addWeek()));
}
Then use it in your controller like this:
App\User::LastWeek()->orderBy('balance', 'DESC')->limit(3)->get();
Let me know if it is working..
Upvotes: 1