Novice
Novice

Reputation: 393

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

Upvotes: 0

Views: 160

Answers (3)

Keopi98
Keopi98

Reputation: 1

You can use the function countBy as follows:

$users = User::select('name')->get()->countBy('name');

And in your blade use:

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

See laravel documentation

Upvotes: 0

Hedayatullah Sarwary
Hedayatullah Sarwary

Reputation: 2844

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

Upvotes: 1

Alireza Farokhi
Alireza Farokhi

Reputation: 106

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

Upvotes: 0

Related Questions