I would need to figure out how to insert some data that I get from a DB into chart.js using Laravel. The data is about the created_at and an integer value present in a table (I want the created_at on the x-axis and the value on the y-axis). The data I detect are taken from the DB through this function:
public function FirstDev()
{
$time = DataFromRasp::where('MAC', 'C4:A5:DF:24:05:7E')->pluck('RSSI', 'created_at');
return view('backend.auth.user.singleDevice', compact("time"));
}
The model is:
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use Seld\PharUtils\Timestamps;
class DataFromRasp extends Model
{
use HasFactory;
protected $primaryKey = 'id';
protected $fillable = ['MAC', 'RSSI'];
}
How can I do this?
CodePudding user response:
You forgot to call ->get() or ->first() method.
should be like this
$time = DataFromRasp::where('MAC', 'C4:A5:DF:24:05:7E')->get()
->pluck('RSSI', 'created_at');
or
$time = DataFromRasp::where('MAC', 'C4:A5:DF:24:05:7E')->first()
->pluck('RSSI', 'created_at');
CodePudding user response:
- You bring data to your Blade files (as usual).
- You set the JS variables by echoing a non-escaped JSON string.
- You import ChartJS library.
- You prepare the canvas.
- You write the JS code that sets the chart properties (or copy it XD).
@php
$labels = ['Red', 'Blue', 'Yellow', 'Green', 'Purple', 'Orange'];
$data = [12, 19, 3, 5, 2, 3];
@endphp
{{-- Setting JS variables from PHP --}}
<script>
const labels = {!! json_encode($labels) !!};
const data = {!! json_encode($data) !!};
</script>
<canvas id="myChart" width="400" height="400"></canvas>
<script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/chart.min.js"></script>
<script>
const ctx = document.getElementById('myChart').getContext('2d');
const myChart = new Chart(ctx, {
type: 'bar',
data: {
labels: labels,
datasets: [{
label: '# of Votes',
data: data,
backgroundColor: [
'rgba(255, 99, 132, 0.2)',
'rgba(54, 162, 235, 0.2)',
'rgba(255, 206, 86, 0.2)',
'rgba(75, 192, 192, 0.2)',
'rgba(153, 102, 255, 0.2)',
'rgba(255, 159, 64, 0.2)'
],
borderColor: [
'rgba(255, 99, 132, 1)',
'rgba(54, 162, 235, 1)',
'rgba(255, 206, 86, 1)',
'rgba(75, 192, 192, 1)',
'rgba(153, 102, 255, 1)',
'rgba(255, 159, 64, 1)'
],
borderWidth: 1
}]
},
options: {
scales: {
y: {
beginAtZero: true
}
}
}
});
</script>