I want to show project name & hours on chart js using Laravel - laravel

I am a beginner at Laravel I am trying to show project name and hours on the chart.js. Unfortunately, data is not showing on the chart; how can I show that?
controller
Chart script
<script>
var ctx = document.getElementById('myChart');
var myChart = new Chart(ctx, {
type: 'bar',
#foreach($hour_logs as $key=>$value)
data: {
//labels: ['Red','Purple'],
labels: {{$value}},
datasets: [{
data: {{$value}},
backgroundColor: [
'rgba(54, 162, 235, 0.2)',
],
borderColor: [
'rgba(54, 162, 235, 1)',
],
borderWidth: 1
}]
},
#endforeach
options: {
scales: {
yAxes: [{
ticks: {
beginAtZero: true
}
}]
}
}
});
</script>
return response
[
"Joylinkhk: 13,",
"HorizonTechnologies: 2,",
"Alahazrat: 9,",
"j2w: 0,"
]
on the left side project name and on the right side hours
dd($hour_logs)
array:4 [
0 => "Joylinkhk: 13,"
1 => "HorizonTechnologies: 2,"
2 => "Alahazrat: 9,"
3 => "j2w: 0,"
]

When passing complex data structures from PHP to JavaScript you will most likely want to be converting them to JSON.
You can convert arrays to JSON using json_encode(). If you are using Larvel collections, they can be converted using ->toJson().

Use Following code
You must send data from controller by parsing like this
implode(',', $label) and
implode(',', $value)
<script>
let label = {!! $label !!}
let value = {!! $value !!}
var ctx = document.getElementById('myChart');
var myChart = new Chart(ctx, {
type: 'bar',
#foreach($hour_logs as $key=>$value)
data: {
//labels: ['Red','Purple'],
labels: label.split(','),
datasets: [{
data: value.aplit(,),
backgroundColor: [
'rgba(54, 162, 235, 0.2)',
],
borderColor: [
'rgba(54, 162, 235, 1)',
],
borderWidth: 1
}]
},
#endforeach
options: {
scales: {
yAxes: [{
ticks: {
beginAtZero: true
}
}]
}
}
});
</script>

Related

how to display multiple sum with chart js and laravel?

I have three table
Table drics
Table country_dric
Table Countries
I just display country name with sum legal from table drics.
I want to display sum column legal, illegal, applicant and mandatory from table drics with country name.
How to display the sum of each column from table drics?
my controller
$drics =DB::table('countries')
->join('country_dric','countries.id','country_dric.country_id')
->join('drics','drics.id','country_dric.dric_id')
->select('name',\DB::raw('sum(legal) as sum'))->groupby('name')
->whereYear('drics.created_at', $year)->get();
$dric_title=[];
$dric=[];
foreach ($drics as $key => $value) {
$dric_title[$key]=$value->name;
$dric[$key]=$value->sum;
}
return view('home.home', compact(' 'dric', 'dric_title'));
js Code
<script>
var ctx = document.getElementById('dric').getContext('2d');
var myChart = new Chart(ctx, {
type: 'bar',
data: {
labels: #json($dric_title),
datasets: [{
label: '# ',
data: #json($dric),
backgroundColor: "rgba(0,31,68,0.8)",
borderColor: "rgb(167, 105, 0)",
borderWidth: 1,
}]
},
options: {
scales: {
yAxes: [{
ticks: {
beginAtZero: true
}
}]
}
}
});
</script>
Try this
Your controller:
$drics =DB::table('countries')
->join('country_dric','countries.id','country_dric.country_id')
->join('drics','drics.id','country_dric.dric_id')
->select('name',\DB::raw('sum(legal) as legal_sum')
,\DB::raw('sum(ilegal) as ilegal_sum')
,\DB::raw('sum(applicant) as applicant_sum')
,\DB::raw('sum(mandatory) as mandatory_sum'))->groupby('name')
->whereYear('drics.created_at', $year)->get();
$dric_title=[];
$dric=[];
foreach ($drics as $key => $value) {
$dric_title[$key]=$value->name;
$dric['legal'][$key]=$value->legal_sum;
$dric['ilegal'][$key]=$value->ilegal_sum;
$dric['applicant'][$key]=$value->applicant_sum;
$dric['mandatory'][$key]=$value->mandatory_sum;
}
return view('home.home', compact(' 'dric', 'dric_title'));
js code:
<script>
var ctx = document.getElementById('dric').getContext('2d');
var myChart = new Chart(ctx, {
type: 'bar',
data: {
labels: #json($dric_title),
datasets: [{
label: 'Legal',
data: #json($dric['legal']),
backgroundColor: "rgba(0,31,68,0.8)",
borderColor: "rgb(167, 105, 0)",
borderWidth: 1,
}, {
label: 'Ilegal',
data: #json($dric['ilegal']),
backgroundColor: "rgba(0,31,68,0.8)", // Change the color to make it different
borderColor: "rgb(167, 105, 0)",
borderWidth: 1,
}, {
label: 'Applicant',
data: #json($dric['applicant']),
backgroundColor: "rgba(0,31,68,0.8)", // Change the color to make it different
borderColor: "rgb(167, 105, 0)",
borderWidth: 1,
}, {
label: 'Mandatory',
data: #json($dric['mandatory']),
backgroundColor: "rgba(0,31,68,0.8)", // Change the color to make it different
borderColor: "rgb(167, 105, 0)",
borderWidth: 1,
}]
},
options: {
scales: {
yAxes: [{
ticks: {
beginAtZero: true
}
}]
}
}
});
</script>
You can use #foreach loop if you want too

How to pass data in Laravel with Chart.js

I want to display total of men and woman from learnings table in chart using Chartjs in Laravel.
My controller
public function index()
{
$men_learning = DB::table('learnings')->where('active', 1)->whereYear('created_at', $year)->sum('men');
$women_learning = DB::table('learnings')->where('active', 1)->whereYear('created_at', $year)->sum('women');
$learning = $men_learning + $women_learning ;
return view('home', compact('learning'));
}
My script in blade view.
<script>
var ctx = document.getElementById('myChart').getContext('2d');
var myChart = new Chart(ctx, {
type: 'bar',
data: {
labels: ['total'],
datasets: [{
label: '# of Votes',
data: [12],
backgroundColor: [
'rgba(255, 99, 132, 0.2)',
],
borderColor: [
'rgba(255, 99, 132, 1)',
],
borderWidth: 1
}]
},
options: {
scales: {
yAxes: [{
ticks: {
beginAtZero: true
}
}]
}
}
});
</script>
How can I propagate loaded statistic from my script to the chart?
public function index()
{
$men_learning = DB::table('learnings')->where('active', 1)->whereYear('created_at', $year)->sum('men');
$women_learning = DB::table('learnings')->where('active', 1)->whereYear('created_at', $year)->sum('women');
return view('home', compact('men_learning', 'women_learning'));
}
<script type="text/javascript">
$(function(){
var ctx = document.getElementById("myChart").getContext('2d');
var myChart = new Chart(ctx, {
type: 'bar',
data: {
labels: ['Men', 'Women'],
datasets: [{
label: 'Men',
data: [{!!$men_learning!!}],
borderWidth: 2,
backgroundColor: 'rgba(40,167,69,1)',
borderWidth: 0,
borderColor: 'transparent',
pointBorderWidth: 0 ,
pointRadius: 3.5,
pointBackgroundColor: 'transparent',
pointHoverBackgroundColor: 'rgba(254,86,83,.8)',
},
{
label: 'Women',
data: [{!!$women_learning!!}],
borderWidth: 2,
backgroundColor: 'rgba(220,53,69,.8)',
borderWidth: 0,
borderColor: 'transparent',
pointBorderWidth: 0,
pointRadius: 3.5,
pointBackgroundColor: 'transparent',
pointHoverBackgroundColor: 'rgba(63,82,227,.8)',
}]
},
options: {
legend: {
display: false
},
scales: {
yAxes: [{
gridLines: {
display: true,
drawBorder: false,
color: '#f2f2f2',
},
ticks: {
beginAtZero: true,
stepSize: 100,
callback: function(value, index, values) {
return value;
}
}
}],
xAxes: [{
gridLines: {
display: false,
tickMarkLength: 15,
}
}]
},
}
});
});
</script>

How to remove transparency from bar charts?

I wonder if there's any way to remove opacity from bar charts built with Chartkick in combination with ChartJS? They always appear semi-transparent, no matter what I do.
This is what I've got so far:
<%=
column_chart(
[
{:data => #invoices},
{:data => #payments}
],
:id => "chart",
:stacked => true,
:colors => ["#E91E63", "#003366"],
:legend => false,
:dataset => {:borderWidth => 0}
)
%>
Thanks for any help.
For two different color with two data-set for proper data comparison Check code snippet
//START Common for all chart
var legend = {
display: true,
position: 'bottom',
labels: {
fontColor: '#000'
}
};
//END Common for all chart
//Dataset
var data1 = {
label: 'Dataset 1',
data: [4, 6, 3, 5, 2, 3],
backgroundColor: 'rgba(255, 99, 132, 1)', //Set 1 for remove transparency
borderColor: 'rgba(255, 99, 132, 1)',
borderWidth: 1
};
var data2 = {
label: 'Dataset 2',
data: [5, 2, 3, 4, 6, 3],
backgroundColor: 'rgba(54, 162, 235, 1)', //Set 1 for remove transparency
borderColor: 'rgba(54, 162, 235, 1)',
borderWidth: 1
};
var Dataset = [data1, data2]
// Dataset
//START Bar chart
var option = {
scales: {
yAxes: [{
gridLines: {
offsetGridLines: true
},
categorySpacing: 5,
ticks: {
beginAtZero: true
}
}]
},
responsive: true,
//maintainAspectRatio: false,
legend: legend,
//onClick: LoadDataInDetails
}
var ctx = document.getElementById('myChart').getContext('2d');
var myChart = new Chart(ctx, {
type: 'bar',
data: {
labels: ['Red', 'Blue', 'Yellow', 'Green', 'Purple', 'Orange'],
datasets: Dataset
},
options: option
});
<script src="https://cdn.jsdelivr.net/npm/chart.js"></script>
<canvas id="myChart"></canvas>
OK, it seems that only RGB colours can be passed into column_chart() (correct me if I'm wrong). This is what I ended up with:
<%=
column_chart(
[
{:data => #invoices},
{:data => #payments}
],
:id => "chart",
:stacked => true,
:colors => [to_rgba("#E91E63"), to_rgba("#003366")],
:legend => false,
:dataset => {:borderWidth => 0}
)
%>
module ColorHelper
def to_rgba(hex_value)
opacity = 1
hex_value = hex_value.gsub('#', '')
rgb_values = hex_value.scan(/../).map{ |x| x.hex }
rgb_values << opacity
"rgba(#{rgb_values.join(',')})"
end
end
Not perfect, but it gets the job done.

Vuejs + Chartjs not showing chart

I’m having problem displaying the chart, Although the data in the getGender() is right, the chart is not displayed. If I get data outside axios it return no data even though I have set it in response.
<div class="x_content">
<canvas id="myChart"></canvas>
</div>
<script>
export default{
props: ['initialCounter'],
data(){
return{
gender:{},
}
},
mounted(){
axios.get('get-gender')
.then((response)=>{
this.getGender(response.data[0])
})
},
methods:{
getGender(data){
console.log(this.gender)
var ctx = document.getElementById("myChart")
var myChart = new Chart(ctx, {
type: 'pie',
data: {
labels: ["Male", "Female"],
datasets: [{
label: '# of Votes',
data: [data.male,data.female],
backgroundColor: [
'rgba(255, 99, 132, 0.2)',
'rgba(54, 162, 235, 0.2)'
],
borderColor: [
'rgba(255,99,132,1)',
'rgba(54, 162, 235, 1)'
],
borderWidth: 1
}]
},
});
}
}
}
</script>

How to solve Chart js mismatched x-axes label and value dynamically in Laravel?

I have encountered a problem using chart js when applying it dynamiccally, which means I get a data from my database and output a bar graph using Chart JS. I found this example which works when a value is 0, but on my situation some data on a specific year cannot be found yet on my database, which leads to a null value. How can I set this empty or null value to zero so that I can achieve this example https://jsfiddle.net/17mw40rx/1/. I want also to show my JS code which I copied from the same sample and applied it to my project. The script works fine but when a year data is missing let say no record found in 2002 and 2005, the data are filled automatically by a wrong year data. I hope you understand my problem. Please I need help from someone about this.
JS Script
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.6.0/Chart.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.6.0/Chart.bundle.js"></script>
<script>
var year = ['2000','2001','2002','2003','2004','2005','2006','2007','2008','2009','2010','2011','2012','2013','2014','2015','2016','2017','2018','2019','2020'];
var female = <?php echo $female; ?>;
var male = <?php echo $male; ?>;
var entranceDataset = {
label: 'Female',
type: 'bar',
yAxesID : "y-axis-1",
data: female,
backgroundColor: 'rgba(0, 204, 0, 0.2)',
borderColor: 'rgba(0, 204, 0,1)',
borderWidth: 1
};
var dataset = [];
dataset.push(entranceDataset);
var exitDataset = {
label: 'Male',
type: 'bar',
yAxesID : "y-axis-1",
data: male,
backgroundColor: 'rgba(54, 162, 235, 0.2)',
borderColor: 'rgba(54, 162, 235, 1)',
borderWidth: 1
};
dataset.push(exitDataset);
var ctx = $('#enrollcanvas');
mainThroughputChart = new Chart(ctx, {
type: 'bar',
data: {
labels: year,
datasets: dataset
},
options: {
scales: {
xAxes : [{
gridLines : {
display : false
},
scaleLabel: {
display: true,
labelString: 'Year'
}
}]
},
}
});
</script>
Laravel Controller and query
$female = Enroll::select(DB::raw("SUM(tot_enroll) as count"))
->orderBy(DB::raw('sy'))
->groupBy(DB::raw("(sy)"))
->where('gender','=', 'Female')
->get()->toArray();
$female = array_column($female, 'count');
$male = Enroll::select(DB::raw("SUM(tot_enroll) as count"))
->orderBy(DB::raw('sy'))
->groupBy(DB::raw("(sy)"))
->where('gender','=', 'Male')
->get()->toArray();
$male = array_column($male, 'count');
return view('home')
->with('female',json_encode($female,JSON_NUMERIC_CHECK))
->with('male',json_encode($male,JSON_NUMERIC_CHECK));
Blade Page
<canvas id="enrollcanvas" name="enrollcanvas" height="280" width="600"></canvas>
Actual Bar Chart Result
Database Table where the bar chart is based from
I think the problem with mismatched data of $female and $male with JS year variable.
var year = ['2000','2001','2002','2003','2004','2005','2006','2007','2008','2009','2010','2011','2012','2013','2014','2015','2016','2017','2018','2019','2020'];
var female = <?php echo $female; ?>;
var male = <?php echo $male; ?>;
Pass the '0' if $female OR $male doesn't have value for each year(Let's say 2000). So your $female and $male should be like:
var year = ['2000','2001','2002','2003', '2004'...];
var female = ['0','34', '0','65', '54',...];
var male = ['0','75', '0','34', '0',...];
Update
Try this below code with full snippet of controller side. Replace enroll with your database table name into this query.
$rsltEnrollData = DB::table('enroll')->selectRaw('sy as sy, gender, SUM(tot_enroll) as count')
->groupBy('sy')
->orderBy('sy')
->get();
$arrFemale = array();
$arrMale = array();
$arrYearData = array();
foreach($rsltEnrollData as $key => $objEnrollData){
if(!isset($arrYearData[$objEnrollData->sy])){
$arrYearData[$objEnrollData->sy]['Male'] = 0;
$arrYearData[$objEnrollData->sy]['Female'] = 0;
}
$arrYearData[$objEnrollData->sy][$objEnrollData->gender] = $objEnrollData->count;
$arrFemale = $arrYearData[$objEnrollData->sy]['Female'];
$arrMale = $arrYearData[$objEnrollData->sy]['Male'];
}
Debug
foreach($rsltEnrollData as $key => $objEnrollData){
print('<pre style="color:red;">');
print_r($objEnrollData);
print('</pre>');
}
exit;
this is a snippet of the script in my project. maybe a little different, but maybe someone needs it. and hope it helps in configuring chart js with laravel and database
JAVASCPT
$(document).ready(function() {
var statistics_chart = document.getElementById("myChart").getContext('2d');
fetch("{{url('chart')}}")
.then(response =>response.json())
.then(json=>{
var myChart = new Chart(statistics_chart, {
type: 'line',
data: {
labels: json.labels,
datasets: json.dataset,
},
options: {
legend: {
display: false
},
scales: {
yAxes: [{
gridLines: {
// display: false,
drawBorder: false,
color: '#f2f2f2',
},
ticks: {
beginAtZero: true,
stepSize: 10000,
}
}],
xAxes: [{
gridLines: {
display: false,
tickMarkLength: 15,
}
}]
},
}
});
})
});
Controller
public function chart()
{
$data = Kas::select([
DB::raw("SUM(debit) as total_debit"),
DB::raw("SUM(kredit) as total_kredit"),
DB::raw("MONTH(created_at) as bln"),
// DB::raw("YEAR(created_at) as year")
])
->whereYear('created_at', 2022)
->groupBy([
'bln'
])
->orderBy('bln')
->get();
$arrBln = [1 => 'Jan','Feb', 'Mar', 'Apr', 'Mei', 'Jun', 'Jul', 'Agu', 'Sep', 'Okt', 'Nov', 'Des'];
$totalD = $totalK = [];
foreach ($data as $tot) {
$totalD[$tot->bln] = $tot->total_debit;
$totalK[$tot->bln] = $tot->total_kredit;
}
foreach ($arrBln as $month =>$name){
if(!array_key_exists($month, $totalD)){
$totalD[$month]= 0;
}
if(!array_key_exists($month, $totalK)){
$totalK[$month]= 0;
}
}
ksort($totalD);
ksort($totalK);
return[
'labels' => array_values($arrBln),
'dataset' => [
[
'label' => 'Pemasukan',
'data' => array_values($totalD),
'borderWidth'=> 2,
'backgroundColor'=> 'rgba(63,82,227,.8)',
'borderWidth' => 0,
'borderColor' =>'transparent',
'pointBorderWidth' => 0,
'pointRadius' => 3.5,
'pointBackgroundColor' => 'transparent',
'pointHoverBackgroundColor' => 'rgba(63,82,227,.8)',
],
[
'label' => 'Pengeluaran',
'data' => array_values($totalK),
'borderWidth'=> 2,
'backgroundColor' => 'rgba(254,86,83,.7)',
'borderWidth' => 0,
'borderColor' =>'transparent',
'pointBorderWidth'=> 0,
'pointRadius'=> 3.5,
'pointBackgroundColor'=> 'transparent',
'pointHoverBackgroundColor'=> 'rgba(254,86,83,.8)',
],
]
];
}

Resources