Skip to main content

generate chart dynamically in laravel by getting data from database

Controller :

public function boardkarya()
{
$labeltmp=array();
// $tmplabel=array();
$valuetmp=array();
$value=array();
$label=array();
// $tmpvalue=array();
$charts=array();
$trainings=Training::where('status','1')->orderBy('id','desc')->get();
$category=Chart::select('category_id')->distinct()->get();
// dd($category);
foreach ($category as $key => $item) {
$tmpcharts=Chart::where('status','1')->where('category_id',$item->category_id)->orderBy('id','desc')->get();
array_push($charts,$tmpcharts);
# code...
}

foreach ($charts as $i => $items) {
$tmplabel=array();
$tmpvalue=array();
foreach ($items as $key => $item) {
array_push($tmplabel,$item->fiscal);
array_push($tmpvalue,$item->total);

}
array_push($labeltmp,$tmplabel);

array_push($valuetmp,$tmpvalue);

}


for($i=0;$i<count($labeltmp);$i++)
{
for($j=0;$j<count($labeltmp[$i]);$j++)
{
array_push($label,$labeltmp[$i][$j]);


}

}


for($i=0;$i<count($valuetmp);$i++)
{
for($j=0;$j<count($valuetmp[$i]);$j++)
{
array_push($value,$valuetmp[$i][$j]);


}

}


return view('frontend.boardkarya',compact('trainings','charts','labeltmp','valuetmp'));
}


labeltmp and value tmp are multidimensional array

blade

<script>
var count=document.getElementById('count').value;

var labeltmp=new Array();
var valuetmp=new Array();
var label=[];
var value=[];
labeltmp = <?php echo json_encode($labeltmp); ?>;
valuetmp = <?php echo json_encode($valuetmp); ?>;
console.log("ads:");
console.log(labeltmp);
console.log(valuetmp);


window.onload = function () {
for(i=0;i<count;i++)
{
for(j=0;j<labeltmp[i].length;j++)
{
label.push(labeltmp[i][j]);
value.push(valuetmp[i][j]);

}
var tmpname='tmpchart'+i;
var ctx = document.getElementById(tmpname).getContext('2d');
Chart.defaults.global.legend.display = false;
var myChart = new Chart(ctx, {
type: 'bar',
data: {
labels: label,
datasets: [{
label: '',
data: value,
backgroundColor: [
'purple',
'red',
'yellow',
'green',
'orange',
'blue',
'maroon'
],
borderWidth: 1
}]
},
options: {
scales: {
yAxes: [{
ticks: {
beginAtZero: true
}
}],
xAxes: [{
gridLines: {
display: false
}
}],
}
}
});

label=[];
value=[];


}







}
</script>



There are reference from fepb site

Now for simple one :

Controller:
public function chart3()
{
// $data = new Banner();
$label=['sa','sn','sz','bx'];
$value=[80,300,200,400];
// dd($label);

return view('frontend.chart3',compact('label','value'));
}


Blade:



<html>
<head>
<script src="https://cdnjs.cloudflare.com/ajax/libs/d3/4.13.0/d3.js"></script>
<script src="{{asset('assets/front/js/c3.js')}}"></script>

<script src="https://canvasjs.com/assets/script/canvasjs.min.js"></script>

<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.5.0/Chart.min.js"></script>



<script>
window.onload = function() {
new Chart(document.getElementById("bar-chart"), {
type: 'bar',
data: {
{{-- labels: ["Africa", "Asia", "Europe", "Latin America"], --}}
labels: [ @php

for($i=0;$i<count($label);$i++)
{
echo "'$label[$i]',";
}
@endphp],

datasets: [
{
label: "Population (millions)",
backgroundColor: ["#3e95cd", "#8e5ea2","#3cba9f","#e8c3b9","#c45850"],
{{-- data:[60,400,200,300] --}}
data:[ @php
for($i=0;$i<count($value);$i++)
{
echo "$value[$i],";
}
@endphp]
}
]
},
options: {
legend: { display: false },
title: {
display: true,
text: 'Predicted world population (millions) in 2050'
}
}
});


var chart = new CanvasJS.Chart("chartContainer", {
animationEnabled: true,
theme: "light2", // "light1", "light2", "dark1", "dark2"
title: {
text: ""
},
axisY: {
title: ""
},
axisX: {
title: ""
},
data: [
{
type: "column",
showInLegend: true,
legendMarkerColor: "grey",
legendText: "",
dataPoints: [
@php
for($i=0;$i<count($label);$i++)
{
echo"{label:'{$label[$i]}',y:{$value[$i]}},";

}
@endphp
]
}]
});
chart.render();






var chart = c3.generate({
data: {

columns: [
@php
echo "['पुरुष'";
for($i=0;$i<count($value);$i++)
{
echo ",$value[$i]";
}

echo "]";
@endphp

{{-- ['पुरुष   ', 200, 0, 90, 240, 130, 220], --}}
// ['महिला', 130, 120, 150, 140, 160, 150],
// ['आंसिक अपाङ्ग', 300, 200, 160, 400, 250, 250],

],
type: 'bar',
types: {
रकम: 'spline',
},

groups: [
['data1', 'data2']
]
},
axis: {
x: {
type: 'category',
categories: [
@php

for($i=0;$i<count($label);$i++)
{
echo "'$label[$i]',";
}


@endphp
]
}
},

bindto: '#chart2'
});
}

</script>
<style>
.grid1{
display:grid;
grid-template-columns: 1fr 1fr;
grid-gap:20px;
}
</style>

</head>
<body>
<div class="grid-container">
<div class="grid1">
<div id="chartContainer"></div>

<div>
<canvas id="bar-chart" width="800" height="450"></canvas>
</div>
<div id="chart2">
</div>

</div>

</div>







</body>

</html>



.........................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................

                                                         BEST WAY HERE BELOW
in view : <canvas id="mychart"></canvas>

controller :

$frontchart=Chart::where('status','1')->where('category','index')->orderBy('id','desc')->get(['date', 'fiscal','total','category_id']);
foreach($frontchart as $item)
{
if(!(in_array($item->date,$date)))
{
array_push($date,$item->date);

}
if(!(in_array($item->category_id,$category_id)))
{
array_push($category_id,$item->category_id);

}
}

return to view with compact category_id , date, frontchart


Inside script of view : 
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.4.0/Chart.min.js"></script>

<script>

var labeltmp=new Array();
var valuetmp=new Array();
var datetmp=new Array();
var datetmp=new Array();
var label=[];
var value=[];
var tmpcount=0;
var category=0;
chart = <?php echo json_encode($frontchart); ?>;
date = <?php echo json_encode($date); ?>;
category_id = <?php echo json_encode($category_id); ?>;
var checkdate=date[0];
// console.log(date);
//console.log(category_id);
//console.log(chart);

function filterbydate(sel)
{
label=[];
value=[];
checkdate=sel.value;
category=sel.getAttribute('data-sth');
console.log('sel attr '+ sel.getAttribute('data-sth'));
console.log('sel value '+ sel.value);
for(j=0;j<chart.length;j++)
{
if(category==chart[j]['category_id']&&chart[j]['date']==checkdate)
{
label.push(chart[j]['fiscal']);
value.push(chart[j]['total']);
}
}
var tmpname='mychart';
var tmpname1='#mychart';
$(tmpname1).remove();
var app='<canvas id="'+tmpname+'"></canvas>';
var chartid='#containerchart';
$(chartid).append(app);
var ctx = document.getElementById(tmpname).getContext('2d');
Chart.defaults.global.legend.display = false;
var myChart = new Chart(ctx, {
type: 'bar',
data: {
labels: label,
datasets: [{
label: '',
data: value,
backgroundColor: [
'purple',
'purple',
'purple',
'purple',
'purple',
'purple',
'purple',
'purple',
],
borderWidth: 1
}]
},
options: {
scales: {
yAxes: [{
ticks: {
beginAtZero: true
}
}],
xAxes: [{
gridLines: {
display: false
}
}],
}
}
});
$('#chartcontainer').remove();
label=[];
value=[];
}

window.onload = function () {
for(j=0;j<chart.length;j++)
{
if(category_id==chart[j]['category_id']&&chart[j]['date']==date[0])
{
label.push(chart[j]['fiscal']);
value.push(chart[j]['total']);
}
}
var tmpname='mychart';
var ctx = document.getElementById(tmpname).getContext('2d');
Chart.defaults.global.legend.display = false;
var myChart = new Chart(ctx, {
type: 'bar',
data: {
labels: label,
datasets: [{
label: '',
data: value,
backgroundColor: [
'purple',
'purple',
'purple',
'purple',
'purple',
'purple',
'purple',
'purple',
'purple',
],
borderWidth: 1
}]
},
options: {
scales: {
yAxes: [{
ticks: {
beginAtZero: true
}
}],
xAxes: [{
gridLines: {
display: false
}
}],
}
}
});
label=[];
value=[];
}
</script>




//somewhere below inside content section
@foreach ($category_id as $k => $item)
<div class="chart">
<div class="title">
<h3>आर्थिक सहायता विवरण</h3>
<select class="custom-select" data-sth="{{$item}}"
onchange="filterbydate(this)">
<option value="" selected>Select</option>
@foreach ($date as $m=>$it)
<option value="{{$it}}" >{{$it}}</option>
@endforeach
</select>
</div>
<div class="content" id="containerchart">
<canvas id="mychart"></canvas>
</div>
</div>
@endforeach







......................................................................................................................................................................................................................................................................................................................................                                                         CREATING CANVAS DYNAMICALLY AND ASSIGN 


Inside Controller :\

public function boardkarya()
{
$date=array();
$category_id=array();
$trainings=Training::where('status','1')->orderBy('id','desc')->get();

$chart=Chart::where('status','1')->where('category','boardkarya')->orderBy('id','desc')->get(['date', 'fiscal','total','category_id']);
foreach($chart as $item)
{
if(!(in_array($item->date,$date)))
{
array_push($date,$item->date);

}
if(!(in_array($item->category_id,$category_id)))
{
array_push($category_id,$item->category_id);

}
}

return view('frontend.boardkarya',compact('trainings','chart','date','category_id'));
}




View File : \

@extends('layouts.frontmaster')
@push('css')
<style>
.canvasjs-chart-canvas {

position: inherit !important;
width: 550px !important;
height: 350px !important;

-webkit-tap-highlight-color: transparent;
cursor: default;
}
</style>


@endpush
@push('js')
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.4.0/Chart.min.js"></script>
<script src="{{asset('assets/front/js/jquery.magnific-popup.min.js')}}"></script>

<script>
var count=document.getElementById('count').value;
var myChart;
var labeltmp=new Array();
var valuetmp=new Array();
var datetmp=new Array();
var datetmp=new Array();
var label=[];
var value=[];
var tmpcount=0;
var category=0;
chart = <?php echo json_encode($chart); ?>;
date = <?php echo json_encode($date); ?>;
category_id = <?php echo json_encode($category_id); ?>;
var checkdate=date[0];
console.log(date);
console.log(category_id);
console.log(chart);

function filterbydate(sel)
{
label=[];
value=[];
checkdate=sel.value;
category=sel.getAttribute('data-sth');
console.log('sel attr'+ sel.getAttribute('data-sth'));
console.log('sel value'+ sel.value);
for(j=0;j<chart.length;j++)
{
if(category==chart[j]['category_id']&&chart[j]['date']==checkdate)
{
label.push(chart[j]['fiscal']);
value.push(chart[j]['total']);
}
}
for(i=0;i<count;i++)
{
var tmpname='tmpchart'+i;
var tmpname1='#tmpchart'+i;
$(tmpname1).remove();
var app='<div class="content-list" ><canvas id="'+tmpname+'"></canvas></div>';
var chartid='#chart'+i;
$(chartid).append(app);
var ctx = document.getElementById(tmpname).getContext('2d');
Chart.defaults.global.legend.display = false;

var myChart = new Chart(ctx, {
type: 'bar',
data: {
labels: label,
datasets: [{
label: '',
data: value,
backgroundColor: [
'purple',
'red',
'yellow',
'green',
'orange',
'blue',
'maroon'
],
borderWidth: 1
}]
},
options: {
scales: {
yAxes: [{
ticks: {
beginAtZero: true
}
}],
xAxes: [{
gridLines: {
display: false
}
}],
}
}
});

}
$('#chartcontainer').remove();
label=[];
value=[];
}
function filterbynav(sel)
{
label=[];
value=[];
//checkdate=sel.value;
category=sel.getAttribute('data-sth');
console.log('sel attr'+ sel.getAttribute('data-sth'));
console.log('sel value'+ sel.value);
for(j=0;j<chart.length;j++)
{
if(category==chart[j]['category_id']&&chart[j]['date']==checkdate)
{
label.push(chart[j]['fiscal']);
value.push(chart[j]['total']);
}
}
for(i=0;i<count;i++)
{
var tmpname='tmpchart'+i;
var tmpname1='#tmpchart'+i;
$(tmpname1).remove();
var app='<div class="content-list" ><canvas id="'+tmpname+'"></canvas></div>';
var chartid='#chart'+i;
$(chartid).append(app);
var ctx = document.getElementById(tmpname).getContext('2d');
Chart.defaults.global.legend.display = false;

var myChart = new Chart(ctx, {
type: 'bar',
data: {
labels: label,
datasets: [{
label: '',
data: value,
backgroundColor: [
'purple',
'red',
'yellow',
'green',
'orange',
'blue',
'maroon'
],
borderWidth: 1
}]
},
options: {
scales: {
yAxes: [{
ticks: {
beginAtZero: true
}
}],
xAxes: [{
gridLines: {
display: false
}
}],
}
}
});

}
$('#chartcontainer').remove();
label=[];
value=[];
}


window.onload = function () {
label=[];
value=[];
for(i=0;i<count;i++)
{
for(j=0;j<chart.length;j++)
{
if(category_id[i]==chart[j]['category_id']&&chart[j]['date']==date[0])
{
label.push(chart[j]['fiscal']);
value.push(chart[j]['total']);
}
}
var tmpname='tmpchart'+i;
var ctx = document.getElementById(tmpname).getContext('2d');
Chart.defaults.global.legend.display = false;
var myChart = new Chart(ctx, {
type: 'bar',
data: {
labels: label,
datasets: [{
label: '',
data: value,
backgroundColor: [
'purple',
'red',
'yellow',
'green',
'orange',
'blue',
'maroon'
],
borderWidth: 1
}]
},
options: {
scales: {
yAxes: [{
ticks: {
beginAtZero: true
}
}],
xAxes: [{
gridLines: {
display: false
}
}],
}
}
});

label=[];
value=[];
}
}

</script>

@endpush
@section('content')
<div class="pb-breadcrumb" style="background:url({{asset('assets/front/images/bg/1.jpg')}});">
<div class="breadcrumb-wrap">
{{-- <h2>Follow steps</h2> --}}

<ul>
<li><a href="{{route('front.index')}}">गृहपृष्ठ</a></li>
<?php $segments = ''; ?> @foreach(Request::segments() as $segment) <?php $segments .= '/'.$segment; ?> <li>
<a href="{{ $segments }}">{{$segment}}</a>
</li>
@endforeach
</ul>
</div>
</div>
<div class="inner-page section">

<div class="container">
<div class="ecotab">
<div class="economy-nav">
<ul>
<li class="economy-link current" data-tab="ecohelp">आर्थिक सहायता</li>
<li class="economy-link" data-tab="otherhelp">सीपमूलक तालिम</li>
</ul>
</div>
<div class="tab-pane">
<div class="eco-content current" id="ecohelp">
<div class="row">
<div class="col-md-4 col-lg-4">
<div class="side-menu">
<ul class="nav nav-tabs" role="tablist">

@foreach ($category_id as $k => $item)

<li class="nav-item">
@if ($k==0)
<a class="nav-link active" href="#chart{{$k}}" role="tab" data-toggle="tab" data-sth="{{$item}}" onclick="filterbynav(this)">{{App\ProductCategory::find($item)->name}}</a>
@else
<a class="nav-link" href="#chart{{$k}}" role="tab" data-toggle="tab" data-sth="{{$item}}" onclick="filterbynav(this)">{{App\ProductCategory::find($item)->name}}</a>

@endif

</li>


@endforeach


</ul>
</div>
</div>
<div class="col-md-8 col-lg-8">
<div class="menu-content">
<div class="card">
<div class="card-body">
<div class="tab-content">
<input type="hidden" id="count" value="{{count($category_id)}}">
@foreach ($category_id as $k => $item)

@if ($k==0)
<div role="tabpanel" class="tab-pane in active" id="chart{{$k}}">
@else
<div role="tabpanel" class="tab-pane" id="chart{{$k}}">
@endif
<div class="card-header">
<h4>{{App\ProductCategory::find($item)->name}} </h4>
<select class="custom-select bar-select" name="pickdate" id="pickdate" data-sth="{{$item}}" onchange="filterbydate(this)">
<option selected value="">Select</option>
@foreach ($date as $m=>$it)
<option value="{{$it}}" >{{$it}}</option>
@endforeach
</select>
</div>
<div class="content-list" id="chartcontainer">
<canvas id="tmpchart{{$k}}"></canvas>
</div>
</div>

@endforeach

</div>

</div>
</div>
</div>

</div>
</div>
</div>
<div class="eco-content " id="otherhelp">
<div class="row">
<div class="col-md-4 col-lg-4">
<div class="side-menu">
<ul class="nav nav-tabs" role="tablist">
@foreach ($trainings as $i=>$item)
<li class="nav-item">
@if ($i==0)
<a class="nav-link active" href="#training{{$i}}" role="tab" data-toggle="tab">{{$item->product_category->name}}</a>
@else
<a class="nav-link" href="#training{{$i}}" role="tab" data-toggle="tab">{{$item->product_category->name}}</a>

@endif

</li>
@endforeach

</ul>
</div>
</div>
<div class="col-md-8 col-lg-8">
<div class="menu-content">
<div class="card">
<div class="card-body">
<div class="tab-content">
@foreach ($trainings as $i=>$item)
@if($i==0)
<div role="tabpanel" class="tab-pane in active" id="training{{$i}}">
@else
<div role="tabpanel" class="tab-pane" id="training{{$i}}">

@endif
<div class="card-header">
<h4>{{$item->title}}</h4>
</div>
<div class="content-list">
<ul>
{!!$item->description!!}
</ul>

</div>
</div>


@endforeach


</div>

</div>
</div>
</div>

</div>
</div>
</div>
</div>
</div>
</div>
</div>

@endsection














Comments

Popular posts from this blog

laravel file manager sorting by time default

Ref :  https://github.com/UniSharp/laravel-filemanager/issues/337 To load files order by "time DESC" you can change the code in vendor/unisharp/laravel-filemanager/src/traits/LfmHelpers.php public function sortFilesAndDirectories($arr_items, $sort_type) { if ($sort_type == 'time') { $key_to_sort = 'updated'; } elseif ($sort_type == 'alphabetic') { $key_to_sort = 'name'; } else { $key_to_sort = 'updated'; } return strcmp($a->{$key_to_sort}, $b->{$key_to_sort}); }); return $arr_items; } with public function sortFilesAndDirectories($arr_items, $sort_type) { if ($sort_type == 'time') { $key_to_sort = 'updated'; } elseif ($sort_type == 'alphabetic') { $key_to_sort = 'name'; } else { $key_to_sort = 'updated'; ...

some important points for web developers and hosting

check dns https://www.whatsmydns.net/ https://check-host.net/ https://www.site24x7.com/ping-test.html attacks https://www.computerhope.com/unix/uping.htm https://vitux.com/linux-ping-command/ https://www.howtoforge.com/linux-ping-command/ https://www.poftut.com/linux-ping-command-tutorial-examples/ https://phoenixnap.com/kb/linux-ping-command-examples https://sandilands.info/sgordon/ping-flooding-dos-attack-in-a-virtual-network https://www.geeksforgeeks.org/ping-command-in-linux-with-examples/

Installing Admin LTE in Laravel

step 1:  Reference---  https://hdtuto.com/article/laravel-56-adminlte-bootstrap-theme-installation-example Step 2 : after completion first reference view this link:    https://github.com/JeroenNoten/Laravel-AdminLTE step 3:  For more additional information view this link:   https://github.com/jeroennoten/Laravel-AdminLTE#2-updating Now you are done statically : https://adminlte.io/blog/integrate-adminlte-with-laravel Steps: 1:  composer require jeroennoten/laravel-adminlte 2: 'providers' => [ .... JeroenNoten\LaravelAdminLte\ServiceProvider::class, ], 3: php artisan vendor:publish --provider="JeroenNoten\LaravelAdminLte\ServiceProvider" --tag=assets 5: php artisan vendor:publish --provider="JeroenNoten\LaravelAdminLte\ServiceProvider" --tag=config 6: php artisan vendor:publish --provider="JeroenNoten\LaravelAdminLte\ServiceProvider" --tag=views 7: for admin pannel php artisan ...