The fundamentals of Chart.js are quite straightforward. First, we must install Chart.js into our project. Depending on the settings of your project, you may be installing it using npm or bower, or you may link to a constructed version via a CDN or clone/build from GitHub. Simply connecting to the created CDN version in the sample's blade file would suffice for this brief example.
A The fundamentals of Chart js are quite straightforward. First, we must install Chart js into our project. Depending on the settings of your project, you may be installing it using npm or bower, or you may link to a constructed version via a CDN or clone/build from GitHub. In our examples, we'll only link to the built-in CDN version for the purposes of this brief demonstration.
We'll just plot the ages of the app users in this case.
We're presuming you've already set up the Laravel auth scaffolding and carried out the required migrations to make a Users table. If not, take a look at the information here or modify it for the model you're using for your chart's data.
Therefore, before creating any users at random, we'll first add an age column to our Users table.
For more information, see our post on how to use faker to create random users, however for this demonstration, let's make a database migration to add an age column by using:
add age to users table php artisan make:migration ?table='users'
To change the up function to: edit this file in the database migrations directory.
Schema::table('Users', function (Blueprint $table) { $table->int('age')->nullable(); });
Run php artisan migrate after that, and your Users table should now contain an age column.
Visit /database/factories/UserFactory now, and add the following at the end of the array:
'age' is represented by $faker->numberBetween($min = 20, $max = 80),
The complete return is thus:
return [ 'name' => $faker->name, 'email' => $faker->unique()->safeEmail, 'email_verified_at' => now(), 'password' => '$2y$10$92IXUNpkjO0rOQ5byMi.Ye4oKoEa3Ro9llC/.og/at2.uheWG/igi', // password 'remember_token' => Str::random(10), 'age' => $faker->numberBetween($min = 20, $max = 80), ];
Run the following commands to build a UsersTableSeeder:
make:seeder UsersTableSeeder in PHP
This will produce UsersTableSeeder.php in the database.
The run function should include the following:
factory(App\User::class, 5)->create();
When this is executed, 5 users will be created; modify 5 to the number of users you need.
After that, we must open DatabaseSeeder.php in /database/seeds and uncomment the code in the run() function.
Finally, execute php artisan db:seed. Five new users should appear, each of whom has an age.
For our Charts page, we will now develop a model, controller, views, and routes.
Run the following command in PHP: make:controller ChartController ?model=Chart.
To the file /app/Http/Controllers/ChartController.php, add the following:
use App\User; use App\Chart; use DB; ... public function index() { // Get users grouped by age $groups = DB::table('users') ->select('age', DB::raw('count(*) as total')) ->groupBy('age') ->pluck('total', 'age')->all(); // Generate random colours for the groups for ($i=0; $i<=count($groups); $i++) { $colours[] = '#' . substr(str_shuffle('ABCDEF0123456789'), 0, 6); } // Prepare the data for returning with the view $chart = new Chart; $chart->labels = (array_keys($groups)); $chart->dataset = (array_values($groups)); $chart->colours = $colours; return view('charts.index', compact('chart')); }
The random colour scheme is one example of the exciting things you can do with the controller's data, though you can also specify hardcoded colours if you'd choose.
In /resources/views/charts/, we must now create an index.blade.php file and add the following (depending on your blade setup and layout; here is an example):
<!doctype html> <html lang="{{ str_replace('_', '-', app()->getLocale()) }}"> <head> <meta charset="utf-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1"> <title>Laravel Chart Example</title> <!-- Bootstrap CSS --> <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css"> <!-- Fontawesome CSS --> </head> <body> <div class="container"> <div class="row"> <div class="col-md-12"> <div class="panel panel-default"> <div class="panel-heading my-2">Chart Demo</div> <div class="col-lg-8"> <canvas id="userChart" class="rounded shadow"></canvas> </div> </div> </div> </div> </div> <script src="https://code.jquery.com/jquery-3.4.1.min.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.7/umd/popper.min.js"></script> <script src="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.min.js"></script> <script src="https://cdn.jsdelivr.net/npm/chart.js@2.8.0"></script> <!-- CHARTS --> <script> var ctx = document.getElementById('userChart').getContext('2d'); var chart = new Chart(ctx, { // The type of chart we want to create type: 'bar', // The data for our dataset data: { labels: {!!json_encode($chart->labels)!!} , datasets: [ { label: 'Count of ages', backgroundColor: {!! json_encode($chart->colours)!!} , data: {!! json_encode($chart->dataset)!!} , }, ] }, // Configuration options go here options: { scales: { yAxes: [{ ticks: { beginAtZero: true, callback: function(value) {if (value % 1 === 0) {return value;}} }, scaleLabel: { display: false } }] }, legend: { labels: { // This more specific font property overrides the global property fontColor: '#122C4B', fontFamily: "'Muli', sans-serif", padding: 25, boxWidth: 25, fontSize: 14, } }, layout: { padding: { left: 10, right: 10, top: 0, bottom: 10 } } } }); </script> </body> </html>
Finally, we need to add the following to /routes/web.php: Route::get('/charts', 'ChartController@index')->name('charts');
Go to at your-project-name.test/charts now.
Although this should serve as a good starting point for your understanding of the fundamentals of charts and graphs in Laravel, you may refer to the Chart.js documentation for more details on customizing your charts.