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');

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

dd($userList) show 1 john and 1 smith


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

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


Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.

Method 1

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)
        <th scope="row">
            {{ $user_value->name }}
            {{ $users_count[$user_key] }}

Method 2

try this in your controller:

$usersList = DB::table('users')->select(DB::raw('name as name, count(*) as 'count'  GROUP BY name'))->get();

and in your *.blade.php file

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

here is the laravel documentation about DB facade and selects :

you can test queries like this in!9/3b70e/1

All methods was sourced from or, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

0 0 votes
Article Rating
Notify of

Inline Feedbacks
View all comments
Would love your thoughts, please comment.x