skip to Main Content

I am using Google Charts to make a graph to show all my citizens ordered by class, everything works correctly except the recovery of the SQL query

My function in my GraphicController is this

public function piechart(){

$result = DB::select(DB::raw("select count(class_id) as citizen_count,citizen_classes.name from assign_citizens LEFT JOIN citizen_classes ON assign_citizens.class_id = citizen_classes.id GROUP BY citizen_classes.id"));
    //dd($result);  // This dd recovery all the data

 $data="";
 foreach ($result as $val){
   $data ="['".$val->name."',     ".$val->citizen_count."],";
 }
 $chartData = $data;
    //dd($chartData ); // This dd only recovery the last register


 return view('backend.graphs.pie_chart',compact('chartData'));
    }

The thing is that if I use dd with my result variable before the foreach loop, I retrieve all my classes and the number of citizens in them correctly

array:3 [▼
  0 => {#1723 ▼
    +"citizen_count": 3
    +"name": "Participativo"
  }
  1 => {#1724 ▼
    +"citizen_count": 1
    +"name": "Inactivo"
  }
  2 => {#1725 ▼
    +"citizen_count": 1
    +"name": "Clase cuatro"
  }
]

When using the foreach loop to retrieve all the data in an understandable format for Google Chart, it only retrieves the last data, if I use dd with the data variable after the foreach loop I get this

"['Clase cuatro',     1],"

Therefore, my graph only shows that one piece of information.

I hope you can help me, sorry for the inconvenience

2

Answers


  1. You’re using $data = instead of $data .=

    Login or Signup to reply.
  2. Alternatively, you can map the result and pass it to json_encode to make your code cleaner and avoid forgetting the concatenation assignment symbol (.=).

    $data = array_map(fn ($row) => [$row->name, $row->citizen_count], $result);
    $chartData = json_encode($data);
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search