Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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);
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading