HTML同様、scriptタグ内でも{{$variable}}と書くとデータが渡る
$ php artisan make:controller AdminController
web.php
Route::get('/', 'HomeController@index'); Route::get('/admin', 'AdminController@index');
AdminController.php
class AdminController extends Controller { // public function index(){ return view('admin/index'); } }
AdminController.php
public function index(){ $postsCount = Post::count(); $categoriesCount = Category::count(); $commentsCount = Comment::count(); return view('admin/index',compact('postsCount','categoriesCount','commentsCount')); }
index.blade.php
<script src="https://cdn.jsdelivr.net/npm/chart.js@2.9.3/dist/Chart.min.js"></script> <script> var ctx = document.getElementById('myChart').getContext('2d'); var myChart = new Chart(ctx, { type: 'bar', data: { labels: ['Posts', 'Categories', 'Comments'], datasets: [{ label: 'Data of CMS', data: [{{$postsCount}},{{$categoriesCount}},{{$commentsCount}}], 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: { yAxes: [{ ticks: { beginAtZero: true } }] } } }); </script>
controllerのdataの取得は、count()以外にも、JSで表現したい内容に合わせてControllerで取得・整形する
JS側ではなくController側で整えるのが一般的か