Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

193
Views
Passing a list from Controller.php to .js file in Laravel

I have a list of numbers in my pageController.php

$half2018 = [235, 1234, 134, 564, 364, 362];
return view('page', 'half2018'=>$half2018); 

I call that variable in my page.blade.php

<canvas id="chart_1" class="chart-canvas" data-info="{{ $half2018 }}"></canvas>

Then at the end of page.blade.php I have

<script src="./assets/js/chart.js"></script>

In my chart.js file I call

let app = document.getElementById('claims_chart_12');
let info = JSON.parse(app.dataset.id);
console.log(info);

For some reason, JSON library is not loaded. Is it a right way to pass the data to .js file?

about 4 years ago · Juan Pablo Isaza
2 answers
Answer question

0

The syntax in your controller should be

$half2018 = [235, 1234, 134, 564, 364, 362];

return view('page', ['half2018' => $half2018]);

or

return view('page', compact('half2018'));

In your blade file, you can set the variable in a data-* attribute after it's converted to valid JSON. Use single quotes for it.

<canvas id="chart_1" class="chart-canvas" data-info='{{ json_encode($half2018) }}'></canvas>

I think this is equivalent to

<canvas id="chart_1" class="chart-canvas" data-info='@json($half2018)'></canvas>

Then, in your js, you can parse this JSON.

let canvas = document.getElementById('chart_1');
let info = JSON.parse(canvas.dataset.id);
console.log(info);
about 4 years ago · Juan Pablo Isaza Report

0

@IGP pointed out my syntax in Controller.php. After I changed the line in chart.js file to

let info = JSON.parse(canvas.dataset.info);
console.log(info)

then I get

[235, 1234, 134, 564, 364, 362]

in my .js file.

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!