首页 > 解决方案 > 具有唯一值和值计数的 Laravel 列表

问题描述

我尝试在表视图中显示数据库中的唯一值以及它们的数量。但我有问题数他们。

id | name  |
------------
 1 | john  |
 2 | john  |
 3 | smith |

我的目标是显示在表格中

name     count
---------------
john       2
smith      1

my controller

    $usersList = DB::table('users')->distinct('name')->get('name');
    
    //dd($usersList);

    return view('dashboard', compact('data'))->with(['usersList '=> $usersList]);  

dd($userList)显示 1john和 1smith

dashboard.blade

 @foreach ($usersList as $row)
       <tr>
           <th scope="row">{{ $row ->name }}</th>                            
           <td>{{ $row->count('name') }}</td>
       </tr>
 @endforeach 

errorCall to undefined method stdClass::count()

标签: phplaravelforeach

解决方案


使用此代码:

$users = User::distinct()->get(['name']);
$users_count = [];
foreach ($users AS $user) {
    $user_count = User::where('name', $user->name)->count('name');
    $users_count[] = $user_count;
}

在您的刀片中使用以下代码:

@foreach ($users AS $user_key => $user_value)
    <tr>
        <th scope="row">
            {{ $user_value->name }}
        </th>                            
        <td>
            {{ $users_count[$user_key] }}
        </td>
  </tr>
@endforeach

推荐阅读