title('用户'); $this->dropdown([ '1' => '当日新增用户', '7' => '7天新增用户', '30' => '当月新增用户', '-1' => '总用户', ]); } /** * 处理请求. * * @return void */ public function handle(Request $request) { switch ($request->get('option')) { case '-1': $this->content($this->getUsers()); $this->up(100); break; case '7': $startAt = Carbon::now()->subDays(7)->toDateString() . ' 23:59:59'; $endAt = Carbon::now()->toDateString() . ' 23:59:59'; $today = $this->getUsers($startAt, $endAt); $this->content($today); // 计算上7天 $startAt = Carbon::now()->subDays(14)->toDateString() . ' 23:59:59'; $endAt = Carbon::now()->subDays(7)->toDateString() . ' 23:59:59'; $this->calcPercent($today, $startAt, $endAt); break; case '30': $startAt = Carbon::now()->subDays(30)->toDateString() . ' 23:59:59'; $endAt = Carbon::now()->toDateString() . ' 23:59:59'; $today = $this->getUsers($startAt, $endAt); $this->content($today); // 计算上个月 $startAt = Carbon::now()->subDays(60)->toDateString() . ' 23:59:59'; $endAt = Carbon::now()->subDays(30)->toDateString() . ' 23:59:59'; $this->calcPercent($today, $startAt, $endAt); break; case '1': default: $startAt = Carbon::now()->toDateString() . ' 00:00:00'; $endAt = Carbon::now()->toDateString() . ' 23:59:59'; $today = $this->getUsers($startAt, $endAt); $this->content($today); // 计算昨天 $startAt = Carbon::now()->subDays()->toDateString() . ' 00:00:00'; $endAt = Carbon::now()->subDay()->toDateString() . ' 23:59:59'; $this->calcPercent($today, $startAt, $endAt); break; } } private function calcPercent($today, $startAt, $endAt) { $yesterday = $this->getUsers($startAt, $endAt); // 百分比 $percent = $yesterday ? ($today - $yesterday) / $yesterday : 0; $percent = round($percent, 2) * 100; $percent > 0 ? $this->up($percent) : $this->down($percent < 0 ? -$percent : $percent); } private function getUsers($startAt = '', $endAt = ''): int { return User::when($startAt, function ($query) use ($startAt) { $query->where('created_at', '>', $startAt); })->when($endAt, function ($query) use ($endAt) { $query->where('created_at', '<=', $endAt); })->count(); } /** * @param int $percent * * @return $this */ public function up($percent) { return $this->footer( " {$percent}% 增加" ); } /** * @param int $percent * * @return $this */ public function down($percent) { return $this->footer( " {$percent}% 减少" ); } /** * 设置卡片底部内容. * * @param string|Renderable|\Closure $footer * * @return $this */ public function footer($footer) { $this->footer = $footer; return $this; } /** * 渲染卡片内容. * * @return string */ public function renderContent() { $content = parent::renderContent(); return <<

{$content}

{$this->renderFooter()}
HTML; } /** * 渲染卡片底部内容. * * @return string */ public function renderFooter() { return $this->toString($this->footer); } }