我只是想问一下如何添加总用户数,包括当我用eloquent过滤它时,数字也会计入列表中的数量。这是我在EloquentUser中的代码。我应该放什么代码,我可以拥有一个变量来计算所有用户甚至我过滤它。我想要一个动态的变量。
public function paginate($perPage, $search = null, $status = null, $emp_status = null, $level = null, $age = null, $gender = null, $civil_status = null, $role_id = null, $birthmonth = null, $company = null, $benefit = null)
{
$query = User::query();
if ($status) {
$query->where('status', $status);
}
if ($search) {
$query->where(function ($q) use ($search) {
$q->where('username', "like", "%{$search}%");
$q->orWhere('email', 'like', "%{$search}%");
$q->orWhere('first_name', 'like', "%{$search}%");
$q->orWhere('last_name', 'like', "%{$search}%");
$q->orWhere('middle_name','like', "%{$search}%");
});
}
if (Auth::user()->hasRole('HR')) {
$query->where('role_id', '=', '3');
};
if($level && $level != "" && $level != "All" ) {
$query->where(function ($q) use ($level) {
$q->where('level', '=', $level);
});
}
if($emp_status && $emp_status != "" && $emp_status != "All") {
$query->where(function ($q) use ($emp_status) {
$q->where('emp_status', '=', $emp_status);
});
}
if ($age && $age != "" && $age != 'All'){
$range = explode('-', $age);
if (count($range) > 1){
$query->whereBetween('birthday', [now()->subYears($range[1]), now()->subYears($range[0])]);
}
else{
$query->where('birthday', '<', now()->subYears($range[0]));
}
}
if($gender && $gender != "" && $gender != "All") {
$query->where(function ($q) use ($gender) {
$q->where('gender', '=', $gender);
});
}
if($civil_status && $civil_status != "" && $civil_status != "All") {
$query->where(function ($q) use ($civil_status) {
$q->where('civil_status', '=', $civil_status);
});
}
if($role_id && $role_id != "" && $role_id != "All"){
$query->where(function ($q) use ($role_id) {
$q->where('role_id', '=', $role_id);
});
}
if($birthmonth && $birthmonth != "" && $birthmonth != "All"){
$query->where(function ($q) use ($birthmonth) {
$q-> whereMonth('birthday', '=', $birthmonth);
});
}
if($company && $company != "" && $company != "All"){
$query = User::whereHas('companies', function ($q) use($company) {
$q->where('company_id','=', $company);
});
}
if($benefit && $benefit != "" && $benefit != "All"){
$query = User::whereHas('benefits', function ($q) use($benefit) {
$q->where('benefit_id','=', $benefit);
});
}
$result = $query->orderBy('id', 'desc')
->paginate($perPage);
if ($search) {
$result->appends(['search' => $search]);
}
return $result;
}
答案 0 :(得分:1)
如果您指的是分页的$ result变量,那么您可以使用
$result->total
答案 1 :(得分:1)
您可以始终对所有查询方法使用count()
方法来获取当前集合计数,但某些实例的paginate除外。
如果我们想获得分页结果的总计数。
您可能需要在使用paginate()时考虑total()
方法。
样品
$data['users'] = User::get();
$data['num'] = $data['users']->count();
return view("YOU_VIEW_HERE",$data);
您可以在视图中使用 $ users ,也可以 $ num 显示必要的值。
答案 2 :(得分:0)
使用此代码
已经奏效了$all = $users->total();
return view('user.list', compact('users', 'statuses','companies','benefits','all'));