foreach data to array laravel

I get the problem when I try looping the data to store in variable for making the pie chart on Laravel

this is my code in controller

// $countUser = DB::select(DB::raw("
//             SELECT r.name AS name, count(u.id) AS countUser
//             FROM users u, role_user ru, roles r
//             WHERE u.id = ru.user_id
//             AND ru.role_id = r.id
//             GROUP BY name "));
$countUser = DB::table(DB::raw('users'))
             ->select(DB::raw('roles.name AS name, count(users.id) AS countUser'))
             ->join('role_user', 'users.id', '=', 'role_user.user_id')
             ->join('roles', 'role_user.role_id', '=', 'roles.id')
             ->groupByRaw('role_user.role_id, name')->get();

$data = " ";
foreach($countUser as $user){
    $data = "['".$user->name."', ".$user->countUser."],";
}

dd($data);

I expect the result like this

enter image description here

but, I get the result only one

enter image description here

When I try this dd($countUser);. This is the result

enter image description here

How to fix it?

>Solution :

In your example you keep overwriting $data, instead lets use Laravel Collection methods to help you.

Map all your entries to the format [$name, $count]. Then use the Collection method implode(), to join the strings with a comma.

$concatenatedUsers = $countUser->map(function ($user) {
    return '[' . $user->name . ', ' . $user->countUser ']';
})->implode(', ');

dd($concatenatedUsers);

Leave a Reply