在我的控制器中:
Optional
我认为:
public function index()
{
$userTotal = User::all();
$userActive = User::where('status', '=', 'Active');
$userInactive = User::where('status', '=', 'Inactive');
$userOnAndOff = User::where('status', '=', 'OnAndOff');
return view('member.home')
->with(compact('userTotal'))
->with(compact('userActive'))
->with(compact('userInactive'))
->with(compact('userOnAndOff'));
}
我正在尝试打印计数值,有没有更好的方法来编码控制器?
答案 0 :(得分:4)
是的,你可以这样做
return view('viewblade', compact('userTotal','userActive','userInactive','userOnAndOff'));
看看这个question及其答案
答案 1 :(得分:3)
通过单个查询和单个变量执行此操作的最佳方法:
public function index()
{
// single query to get total user and status based users count
$data = User::select(DB::raw('COUNT(*) AS total_users'),
DB::raw('SUM(CASE WHEN status = "Active" THEN "Active" END ) AS active_users'),
DB::raw('SUM(CASE WHEN status = "Inactive" THEN "Inactive" END ) AS inactive_users'),
DB::raw('SUM(CASE WHEN status = "OnAndOff" THEN "OnAndOff" END ) AS onoff_users')
)->first();
return view('member.home')->with($data);
}
在
之类的视图文件中使用<div class="card border-success">
<div class="card-horizontal">
<div class="card-body bg-success">
<p class="card-text text-white bg-success text-md-center"><i class="fas fa-users fa-2x"></i></p>
</div>
<div class="card-body text-success">
<p class="card-text">Registered Member: <strong>{{ $total_users }}</strong></p>
<p class="card-text">Active Members: <strong>{{ $active_users }}</strong></p>
<p class="card-text">Active Members: <strong>{{ $active_users }}</strong></p>
<p class="card-text">Inactive Members: <strong>{{ $inactive_users }}</strong></p>
</div>
</div>
</div>
希望有帮助。谢谢。
答案 2 :(得分:1)
尝试一下
public function index()
{
$userTotal = User::all();
$userActive = User::where('status', '=', 'Active');
$userInactive = User::where('status', '=', 'Inactive');
$userOnAndOff = User::where('status', '=', 'OnAndOff');
return view('member.home', compact('userTotal','userActive','userInactive','userOnAndOff'));
}