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()

Answers:

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

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)
      <tr>
        <th scope="row">{{ $row->name }}</th>                            
        <td>{{ $row->count }}</td>
      </tr>
    @endforeach

here is the laravel documentation about DB facade and selects : https://laravel.com/docs/4.2/queries#selects

you can test queries like this in http://sqlfiddle.com/#!9/3b70e/1


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

0 0 votes
Article Rating
Subscribe
Notify of
guest

0 Comments
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x