Search code examples
phplaravelforeach

Laravel list with unique values and count of values


Im trying show unique values from database with count of them in table view. But i have problem count them.

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

my goal is show in table

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) show 1 john and 1 smith

dashboard.blade

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

error : Call to undefined method stdClass::count()


Solution

  • Use this code:

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

    And in your blade use this code:

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