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