How to pass data in laravel with chart.js?

by jasen_gottlieb , in category: PHP Frameworks , 5 months ago

How to pass data in laravel with chart.js?

Facebook Twitter LinkedIn Telegram Whatsapp

1 answer

by ryan.murray , 5 months ago

@jasen_gottlieb 

To pass data in Laravel with Chart.js, you can follow these steps:

  1. First, you need to retrieve the data from your database or any other source in your Laravel controller. You can use Eloquent ORM to retrieve data from the database.
  2. Once you have retrieved the data, you need to pass it to your blade view file. You can do this by using the compact() method or by passing the data as an array to the view() method:
1
2
$data = [10, 20, 30, 40, 50];
return view('chart', compact('data'));


  1. In your blade view file, you can use the passed data to initialize your Chart.js chart. You can do this by using a element with a unique ID and by using JavaScript to create the chart:
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
<canvas id="myChart" width="400" height="400"></canvas>

<script>
    var ctx = document.getElementById('myChart').getContext('2d');
    var myChart = new Chart(ctx, {
        type: 'bar',
        data: {
            labels: ['January', 'February', 'March', 'April', 'May'],
            datasets: [{
                label: 'Data',
                backgroundColor: 'rgba(255, 99, 132, 0.2)',
                borderColor: 'rgba(255, 99, 132, 1)',
                borderWidth: 1,
                data: {!! json_encode($data) !!}
            }]
        },
        options: {
            scales: {
                yAxes: [{
                    ticks: {
                        beginAtZero: true
                    }
                }]
            }
        }
    });
</script>


  1. Make sure to include the Chart.js library in your project. You can do this by including a CDN link in your blade view file or by installing Chart.js using npm.
  2. Finally, when you load the view in your browser, you should see the chart displaying the data that you passed from your Laravel controller.


That's it! You have successfully passed data in Laravel with Chart.js.