kya
kya

Reputation: 1828

Passing data from a controller to ChartJS - Laravel

I would like to pass data from my laravel controller to chartjs javascript file. But at the moment, I can only get the data to home.blade and not the javascript file. below is my controller:

 public function index()
{


    $visits = Visitdetail::all();
    $countVisit = $visits->count();


    $totalSchools = School::all()->count();
    $totalProjects = Project::all()->count();

    $recentVisits = Visitdetail::all()->sortByDesc('created_at')->take(5);


    $visitsYear = Visit::where('created_at','>=', Carbon::now()->startOfYear())->take(5)->get();





    return view('home',['countVisit'=>$countVisit,'recentVisits'=>$recentVisits, 'totalSchools'=>$totalSchools,'totalProjects'=>$totalProjects,
        'yearVisits'=>$visitsYear]);
}

On home.blade, I just have a canvas and the below is the code:

<div class="box-body">                    
  <div class="chart">
     <canvas id="barChart" style="height:227px"></canvas>
  </div>
</div>

On the chartJS file, I have the following code (Filename: dashboard.js), located in the public/js/dashboard.js directory:

// Get context with jQuery - using jQuery's .get() method.
    var barChartCanvas = $('#barChart').get(0).getContext('2d');
    // This will get the first returned node in the jQuery collection.
    var barChart            = new Chart(barChartCanvas);

    var barChartData = {
      labels  : ['Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun'],
      datasets: [
        {
          label               : 'Electronics',
          fillColor           : 'rgba(38,198,218,1)',
          strokeColor         : 'rgba(38,198,218,0)',
          pointColor          : '#26c6da',
          pointStrokeColor    : 'rgba(38,198,218,0)',
          pointHighlightFill  : '#fff',
          pointHighlightStroke: 'rgba(38,198,218,1)',
          data                : [5, 4, 3, 7, 5, 10, 3]
        },
        {
          label               : 'Digital Goods',
          fillColor           : 'rgba(30,136,229,1)',
          strokeColor         : 'rgba(30,136,229,0)',
          pointColor          : 'rgba(30,136,229,0)',
          pointStrokeColor    : '#1e88e5',
          pointHighlightFill  : '#fff',
          pointHighlightStroke: 'rgba(30,136,229,1)',
          data                : [3, 2, 9, 5, 4, 6, 4]
        }
      ]
    };

I tried to set the values of the the dataset with dynamic blade variable, where on data, I had:

data                : [{{$countVisits}}, {{recentVisits}}]

However, this didn't work. Any assistance that could point me to the right direction will be appreciated.

Upvotes: 1

Views: 2823

Answers (1)

Džuris
Džuris

Reputation: 2234

You can't insert a variable from Laravel into an asset file. You can only insert in views. Assets are supposed to be the part that doesn't change across requests.

The usual way is to insert the data in the view and store it in a global JS variable that the script can access.

I.e. in home.blade.php do this:

<script>
var datasets = [@json($countVisits), @json($recentVisits)]

// or using an object
var theDatasets = {
    countVisits: @json($countVisits),
    recentVisits: @json($recentVisits)
}

//or directly
var countVisits = @json($countVisits)
var recentVisits = @json($recentVisits)
</script>

<!-- include your dashboard.js afterwards -->

And then you can use the variable inside the dashboard.js in a way that corresponds to how you stored it:

//from array
datasets[0]

//from object
theDatasets.countVisits

//directly
countVisits

The other ways to solve this would be

  • load data via AJAX. But this shifts the problem that you have to give or hardcode the route
  • put all that chart javascript in the view (I would do this if it's only used in one view, you can also include it from a subview if you want the code organized)
  • create the javascript file as a dynamic view and let blade insert the data into it. I have never seen this done and it doesn't seem appropriate, but it's probably possible.

Upvotes: 1

Related Questions