Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I get current week's count data from table in Laravel

I am trying to get this current week's data from my table

I have the following code which gives me 31 days of data (A month but it's separated which is what I need)

$stats["tmv"] = "";
$stats["tmd"] = "";
$stats["tru"] =  array();

        for ($i=1; $i <= 31; $i++) {
            $stats["tmv"] .= DB::table('stats')->select(DB::raw('*'))->where(DB::raw('DAY(created_at)'), '=', $i)->where('stats_type', "mv")->count();
            $stats["tmd"] .= DB::table('stats')->select(DB::raw('*'))->where(DB::raw('DAY(created_at)'), '=', $i)->where('stats_type', "md")->count();
            $stats["tru"][$i] = DB::table('users')->select(DB::raw('*'))->where(DB::raw('DAY(created_at)'), '=', $i)->count();

            if ($i != 31) {
                $stats["tmv"] .= ",";
                $stats["tmd"] .= ",";
            }
        }

Output:

"tmv" => "11,4,1,13,0,5,15,2,0,24,1,7,17,18,45,14,31,61,3,1,4,1,1,27,30,47,18,60,10,0,156"

How do I edit my query to select this current week's data but still output the count like:

"11,4,1,13,0,5,15"
like image 308
DIGITALCRIMINAL Avatar asked Mar 18 '17 14:03

DIGITALCRIMINAL


People also ask

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.

How do you get the last 30 days in Laravel?

use Carbon\Carbon; $users = DB::table("users") ->select('id') ->where('accounttype', 'standard') ->where('created_at', '>', now()->subDays(30)->endOfDay()) ->all();


1 Answers

Your code generates a lot of queries which is really bad. There are many ways to get data you want with one query. For example, using Eloquent:

Stats::where('created_at', '>', Carbon::now()->startOfWeek())
     ->where('created_at', '<', Carbon::now()->endOfWeek())
     ->get();

If you want to get data for another week and not the current one, use another Carbon object like Carbon::parse('2017-05-01') instead of Carbon::now()

like image 106
Alexey Mezenin Avatar answered Oct 22 '22 07:10

Alexey Mezenin