How to use new variable in Google Chart? - php

I've made a new variable with this code :
$countId2 = Event::selectRaw("category_id,count(id) as count")
->groupBy('category_id')
->orderBy('count','DESC')->skip(1)
->take(1)
->limit('1')
->get();
and $countId2 results :
{"category_id":"15","count":"4"}
It's exactly what I wanted.To count first 3 categories and put it into Google Chart.
Here is my Google Chart code:
<script>
var data12 = {{ $countEvents }};
var data13 = {{ $countNews }};
var data14 = {{ $countOpinion }};
google.charts.load("current", {packages:["corechart"]});
google.charts.setOnLoadCallback(drawChart);
function drawChart() {
var data = google.visualization.arrayToDataTable([
['Task', 'Hours per Day'],
['Events', data12],
['News', data13],
['Opinions', data14],
]);
var options = {
title: 'My Daily Activities',
pieHole: 0.4,
};
var chart = new google.visualization.PieChart(document.getElementById('donutchart'));
chart.draw(data, options);
}
</script>
Previously, I used data 12,data13 and data14 to get an exactly number.Now, I get category ID with count numbers.How to use this variable instead of data12,data13 and data14? I want to add it to my Goole Chart to be more dinamic.
I want to use category_id instead of Events/News and Opinions, and number of counts instead of data13,data 12 and data14.

Related

Google Bar Chart with Laravel and SQL Query

I am trying to make and display a Bar Chart using Google Charts on my Laravel dashboard,
the query I am trying to use is Supposed to join two tables and fetch the columns to get the average according to which department the training was done under.
This is the query I am using:
SELECT AVG(training_hours.Hours) as AverageTraining, training_hours.dept_id, departments.department_name
FROM training_hours INNER JOIN employees ON training_hours.employee_id = employees.id
INNER JOIN departments ON training_hours.dept_id = departments.id
WHERE training_hours.dept_id = employees.dept_id
GROUP BY departments.department_name;
When i try to convert into Laravel eloquent I am getting something like this ->
$barChart=DB::table('training_hours')
->Join('employees','employees.id','=','training_hours.employee_id')
->Join('departments','departments.id','=','training_hours.dept_id')
->where('training_hours.dept_id','`employees.dept_id`')
->select(DB::raw('AVG(training_hours.Hours) AS AverageTraining'),'training_hours.dept_id','departments.department_name')
->groupBy('departments.department_name')
->get();
Now how do I display this in the bar chart on my dashboard?
I already have another chart being displayed, which is a Pie Chart the codes for that are like this:
Controller
$userId = Auth::id();
$users = User::paginate(10);
$hoursDone=DB::table('training_hours')
->where('employee_id',$userId)
->select(DB::raw('SUM(Hours) AS TrainingHoursDone'))
->get();
$hoursLeft=DB::table('employees')
->where('id',$userId)
->join('training_hours', 'employees.id', '=', 'training_hours.employee_id')
->selectRaw('TrainingHoursRequired - sum(Hours) as HoursLeft')
->get();
$chartData="";
foreach($hoursLeft as $hLeft){
$chartData.="['".$hLeft->HoursLeft."', ".$hLeft->HoursLeft."],";
}
foreach($hoursDone as $hDone){
$chartData.="['".$hDone->TrainingHoursDone."', ".$hDone->TrainingHoursDone."],";
}
$arr['chartData']=rtrim($chartData,",");
return view('admin.dashboard.index', compact('users', 'chartData'));
Dashboard.blade
<script type="text/javascript" src="https://www.gstatic.com/charts/loader.js"></script>
<script type="text/javascript">
google.charts.load('current', {
'packages': ['corechart']
});
google.charts.setOnLoadCallback(drawChart);
function drawChart() {
var data = google.visualization.arrayToDataTable([
['Training Hours Done', 'Training Hours Left'],
<?php echo $chartData; ?>
]);
var options = {
title: 'Hours Completed Vs Hours Remaining',
legend: 'none',
pieHole: 0.4,
tooltip: { trigger: 'none' },
slices: {
0: {color: 'orange'},
1: {color: 'blue'}
}
};
var chart = new google.visualization.PieChart(document.getElementById('piechart'));
chart.draw(data, options);
}
</script>
How can I do the bar chart? Please do help me with this.

How to get data from Laravel db into googlechart?

I want to introduce my counts into this GoogleChart. I want to count all id from table News/Opinions/Events etc.I want to be able to put numbers of all records from News/Opinions/Events etc. If in "News" table I have 10 news, i want to count them and introduce it to ['News', 'All news HERE'],
And the second, I want to add it into this code:
<script>
google.charts.load("current", {packages:["corechart"]});
google.charts.setOnLoadCallback(drawChart);
function drawChart() {
var data = google.visualization.arrayToDataTable([
['News', 'All news HERE'],
['Events', No of events from db],
]);
var options = {
title: 'My Daily Activities',
pieHole: 0.4,
};
var chart = new google.visualization.PieChart(document.getElementById('donutchart'));
chart.draw(data, options);
}
</script>
You can just query your database to get all counts that you needed (should be fast if you don't query many tables).
public function myControllerAction() {
$dbData = DB::selectOne('
select
(select count(*) from news) as News,
(select count(*) from events) as Events,
(select count(*) from someothertable) as Someotherdata
');
return view('my-view', compact('dbData'));
}
After this you can use $dbData->News, $dbData->Events, $dbData->Someotherdata and put it anywhere you like in your code.
You can even simplify your future development by using Laravel's Collection and generating a ready to use array for google charts:
public function myControllerAction() {
$dbData = DB::selectOne('
select
(select count(*) from news) as News,
(select count(*) from events) as Events,
(select count(*) from someothertable) as Someotherdata
');
$collection = new \Illuminate\Support\Collection($dbData);
$data = $collection->flatMap(function($value, $key) {
// We will use name of the key as the label for chart (News, Events, Someotherdata)
return [[$key, $value]];
})->toArray();
return view('my-view', compact('data'));
}
And just use Blade's #json directive to render the json where you need it:
<script>
google.charts.load("current", {packages:["corechart"]});
google.charts.setOnLoadCallback(drawChart);
function drawChart() {
// Here is the changed part, notice the #json($data) here
var data = google.visualization.arrayToDataTable(#json($data));
var options = {
title: 'My Daily Activities',
pieHole: 0.4,
};
var chart = new google.visualization.PieChart(document.getElementById('donutchart'));
chart.draw(data, options);
}
</script>
I really can't fully understand what you are trying to do but I will show you whole concept
in web.php route file :
Route::get('/newsCount', 'NewsController#count');
in NewsController.php controller file :
public function count()
{
$CountOfNews = News::all()->count(); // Get count of all your news
// Now you can use one of these two ways
// Pass data to view way 1
return View::make("user/NewsCount", compact('CountOfNews'));
// Pass data to view way 2
return View::make("user/NewsCount")->with(array('Count'=>$CountOfNews));
}
and into your balde.php view file you should do like this :
<script>
alert({{$CountOfNews}});
</script>

Google Pie Chart php mysql

**
I used Google Pie chart using PHP MySQL. If I put my mouse on the
chart it only shows 2 column data from the row. But there are three
columns in that table & I want to show all the columns from the row. I
have written this code to show 3rd column but it doesn't work.
**
var data = google.visualization.arrayToDataTable([
['Problems', 'Sufferer', 'Solutions'],
<?php
while($row = $res->fetch_assoc()){
echo "['".$row['Problems']."',".$row['sum(Sufferer)'].", '".$row['Solutions']."'],";
}
?>
]);
How can I solve this problem? picture of my Pie Chart output example
Google Pie chart only supports 2 columns refer Google Pie Chart
The first one is the slice label and the second one is the slice value.
If you wish to add more information to your chart, you can make use of the tooltip which is displayed on hover.
For more information on columns and roles, refer Column Roles
By default only the slice label and slice value with percentage will be shown in the tooltip of the chart.
This can be customized by passing data in the below format
Data format
var data = google.visualization.arrayToDataTable([
['Pizza', 'Popularity', {type:'string', role:'tooltip'}],
['Pepperoni', 33, "Most popular"],
]);
If you wish to customize the rendering of the tooltip, it can be achieved by passing HTML data as the content of the tooltip.
For more information on tooltips and customizing HTML content, refer Tooltips
Example
google.charts.load('current', {'packages':['corechart']});
google.charts.setOnLoadCallback(drawChart);
function drawChart() {
var data = google.visualization.arrayToDataTable([
['Pizza', 'Popularity', {type:'string', role:'tooltip'}],
['Pepperoni', 33, "Most popular"],
['Hawaiian', 26, "Popular"],
['Mushroom', 22, "Somewhat popular"],
['Sausage', 10, "Less popular"]
]);
var options = {
title: 'Pizza Popularity'
};
var chart = new google.visualization.PieChart(document.getElementById('piechart'));
chart.draw(data, options);
}
<script type="text/javascript" src="https://www.gstatic.com/charts/loader.js"></script>
<div id="piechart" style="width: 900px; height: 500px;"></div>

remove pagination on google pie chart

i have following code to display pie chart.
<script>
google.charts.load('current', {'packages':['corechart']});
// Set a callback to run when the Google Visualization API is loaded.
google.charts.setOnLoadCallback(drawChart);
//google.charts.setOnLoadCallback(drawChartTwo);
//google.charts.setOnLoadCallback(drawChartThree);
// Callback that creates and populates a data table,
// instantiates the pie chart, passes in the data and
// draws it.
function drawChart() {
// Create the data table.
var data = google.visualization.arrayToDataTable([
['Type', 'Duration'],
<?php
foreach($val as $data){
echo "['".$data['type']."', ".$data['duration']."],";
}
?>
]);
// Set chart options
var options = {'title':'Duration Analysis',
'width':830,
'height':300,
'is3D': true,
pieSliceText : 'none',
};
// Instantiate and draw our chart, passing in some options.
var chart = new google.visualization.PieChart(document.getElementById('chart_div'));
chart.draw(data, options);
</script>
and its working fine. but, now when i see chart on my browser i see it like.
in the image i see list of values in pagination with 3 page. but i want it to display right side of my chart without pagination. any possibility to display 3 colomns instead of 3 pagination page??? Please help me.

Grouping rows by column value/category in a Google pie chart

I have a table that looks like the following:
sub_note | item_amount | sub_cat |
---------------------------------------|
Spotify | $5.99 | entertainment |
Vodafone | $35 | phone |
Netflix | $5.99 | entertainment |
I want to display a Google pie chart that tells me how much is being spent per category i.e. Entertainment, Phone etc.
I have used the following adaptation of the Google Quick Start example, but all I'm seeing is a blank chart with 'No data'.
<script type="text/javascript">
// Load the Visualization API and the corechart package.
google.charts.load('current', {'packages':['corechart']});
// Set a callback to run when the Google Visualization API is loaded.
google.charts.setOnLoadCallback(drawChart);
// Callback that creates and populates a data table,
// instantiates the pie chart, passes in the data and
// draws it.
function drawChart() {
// Create the data table.
var data = new google.visualization.DataTable();
data.addColumn('string', 'Category');
data.addColumn('number', 'Total');
data.addRows([
<?php
$query = "SELECT SUM(sub_amount) AS sub_cat, subs_total FROM subscriptions WHERE sub_user_id ='".$user_id."' GROUP BY sub_cat ORDER BY sub_cat";
$exec = mysqli_query($connect,$query);
while($row = mysqli_fetch_array($exec)){
echo "['".$row['sub_cat']."',".$row['subs_total']."],";
}
?>]);
// Set chart options
var options = {'title':'Spending by Category',
'width':600,
'height':400};
// Instantiate and draw our chart, passing in some options.
var chart = new google.visualization.PieChart(document.getElementById('chart_div'));
chart.draw(data, options);
}
</script>
It's clear that there's something wrong with the query code and how it's being grouped, but I'm scratching my head trying to figure this out.
Any pointers would be great!
UPDATE: Thanks to #WhiteHat for the SQL correction, here's the functioning code:
<script type="text/javascript">
// Load the Visualization API and the corechart package.
google.charts.load('current', {'packages':['corechart']});
// Set a callback to run when the Google Visualization API is loaded.
google.charts.setOnLoadCallback(drawChart);
// Callback that creates and populates a data table,
// instantiates the pie chart, passes in the data and
// draws it.
function drawChart() {
// Create the data table.
var data = new google.visualization.DataTable();
data.addColumn('string', 'Category');
data.addColumn('number', 'Total');
data.addRows([
<?php
$query = "SELECT sub_cat, SUM(sub_amount) as subs_total FROM subscriptions WHERE sub_user_id ='".$user_id."' GROUP BY sub_cat ORDER BY sub_cat";
$exec = mysqli_query($connect,$query);
while($row = mysqli_fetch_array($exec)){
echo "['".$row['sub_cat']."',".$row['subs_total']."],";
}
?>]);
// Set chart options
var options = {'title':'How Much Pizza I Ate Last Night',
'width':600,
'height':400};
// Instantiate and draw our chart, passing in some options.
var chart = new google.visualization.PieChart(document.getElementById('chart_div'));
chart.draw(data, options);
}
</script>
try this sql...
$query = "SELECT sub_cat, SUM(sub_amount) as subs_total FROM subscriptions WHERE sub_user_id ='".$user_id."' GROUP BY sub_cat ORDER BY sub_cat";
The category should be the first column and subtotal second.
Please can you test if your sql code return something?
I would help you if you give to me the correct dataset in your SQL.
Try to do an echo or vardump outside your javascript to know if your SQL is Good.

Categories