如何通过 laravel 中的浏览量统计 table 中的用户数?

How to count the number of users from a table through views in laravel?

我正在处理 laravel 5.5,我正在尝试计算 table 中的用户数量并显示视图中的结果。

但是我遇到了一个错误

"Undefined Variable: count"

这是控制器内部的功能:

public function admin(){

   $count = DB::select('select count(*) as total from users');
   return view('home',['count' => $count]);
}

这是视图中的代码'home':

<tr>
   <td> Total Users </td>
   <td> Total Coaches </td>
   <td> {{$count}} </td>
</tr>

您在这样的字符串中给出了变量 ['count => $count'],所以它不起作用。

在您的控制器中尝试如下代码:

public function admin()                                                    
{                                              
   $count = DB::select('select count(*) as total from users');
   return view('home', ['count' => $count[0]->total]);                      
}                                                                  

问题在这里:

return view('home',['count => $count']);  
// Single quotation is on wrong place, array key will be wrapped with single quotation not the variable

改为:

return view('home',['count' => $count]);

根据您的看法尝试:

{{ $count[0]->total }}

对我有用

  use Illuminate\Support\Carbon;
        
        
    $users_count = User::count();
    $users_today = User::where('created_at','>=',Carbon::now()->startOfDay())->count();
    $users_this_week = User::where('created_at','>=',Carbon::now()->startOfWeek(\Carbon\Carbon::SATURDAY)->startOfDay())->count(); // default startOfWeek() is Monday
    $users_this_month = User::where('created_at','>=',Carbon::now()->firstOfMonth()->startOfMonth()->startOfDay())->count();
    $users_this_year = User::where('created_at','>=',Carbon::now()->firstOfMonth()->startOfMonth()->startOfDay())->count();