Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Laravel: How to get count of all records created within in current week as of yesterday

I want to get count of one week old created records as of yesterday in laravel using created_at time stamp, I have:

//week date range upto current day
$name_current_day = date("l");
$name_current_week = date("Y-m-d",strtotime('monday this week')).'to'.date("Y-m-d",strtotime("$name_current_day this week"));

//query to get count
foreach($name_list as $name){
                //created in week
                $data[$network->name.'_week'] = Info::select( DB::raw('DATE(`created_at`) as `date`'),DB::raw('COUNT(*) as `count`'))
                    ->where('created_at', '>', $name_current_week)
                    ->where('name',$name->f_name)
                    ->groupBy('date')
                    ->orderBy('date', 'DESC')
                    ->lists('count', 'date');
           }

When I run this query, I am not getting accurate results, Is this the cirrect way to get last 7 days records in Laravel.

like image 858
user3871434 Avatar asked Dec 12 '22 04:12

user3871434


2 Answers

You need to compare date() as well, and it's easier to use Carbon, though you don't need that. It's up to you.

EDIT: your question is a bit unclear, but it seems that you don't want week-old, but only current week's results.

Anyway, this will work for you:

// week old results:
// $fromDate = Carbon\Carbon::now()->subDays(8)->format('Y-m-d');
// $tillDate = Carbon\Carbon::now()->subDay()->format('Y-m-d');

// this week results
$fromDate = Carbon\Carbon::now()->subDay()->startOfWeek()->toDateString(); // or ->format(..)
$tillDate = Carbon\Carbon::now()->subDay()->toDateString();


Info::selectRaw('date(created_at) as date, COUNT(*) as count'))
    ->whereBetween( DB::raw('date(created_at)'), [$fromDate, $tillDate] )
    ->where('name',$name->f_name)
    ->groupBy('date')
    ->orderBy('date', 'DESC')
    ->lists('count', 'date');
like image 73
Jarek Tkaczyk Avatar answered Apr 27 '23 18:04

Jarek Tkaczyk


You can use Carbon for this, which makes working with dates easier in Laravel. It's included with the framework. You can then do this:

$yesterday = Carbon::now()->subDays(1);
$one_week_ago = Carbon::now()->subWeeks(1);

foreach($name_list as $name){
    //created in week
    $data[$network->name.'_week'] = Info::select( DB::raw('DATE(`created_at`) as `date`'),DB::raw('COUNT(*) as `count`'))
        ->where('created_at', '>=', $one_week_ago)
        ->where('created_at', '<=', $yesterday)
        ->where('name',$name->f_name)
        ->groupBy('date')
        ->orderBy('date', 'DESC')
        ->lists('count', 'date');
}
like image 39
lowerends Avatar answered Apr 27 '23 18:04

lowerends