Getting started with Charts in Laravel 7
A brief guide on how to present data from your Laravel app in a chart or graph.
Charts of all types, shapes and sizes are a familiar sight across the web; especially within SAAS apps, news articles, or analytics tools, and if you’re developing an application you’ve probably considered including some sort of graph or chart functionality to display data.
Getting a basic chart to display in Laravel is a simple process using a JavaScript charting solution, in this example we will be using Chart.js.
Overview:
The basics of Chart.js are pretty simple; first we need to install Chart.js into our project, depending on your project configuration you may be installing it using npm or bower, or you can link to a built version via a CDN, or clone/build from GitHub. For this quick example we’ll just be linking to the built CDN version in our example’s blade file.
A <canvas>
node with an id
is added to your page and then a <script>
is added where the labels, dataset, colours and other settings are configured for the chart to render on the page.
You can simply hard-code all of these values into the <script>
but that doesn't make a very useful solution for dynamic data, so next we'll look at creating data in the correct format to populate the dataset, labels and backgroundColor
options.
The Data:
For this example we’ll simply chart the ages of the users in our app.
We’re assuming you have the Laravel auth
scaffolding already installed and have run the necessary migrations to create a Users
table. Check out the info here if not or adapt for the Model
you are using for your chart data.
So firstly, we’re going to add an age
column to our Users
table, and then create some random users.
You can check out our article on using faker to create random Users for more detail but for this example we’ll create a database migration to add an age column by using:
php artisan make:migration --table='users' 'add_age_to_users_table'
Edit this file in /database/migrations/
to update the up
function to:
Schema::table('Users', function (Blueprint $table) {
$table->int('age')->nullable();
});
Then run php artisan migrate
and you should now have an age
column in your Users
table.
Now go to /database/factories/UserFactory
and at the end of the array add:
'age' => $faker->numberBetween($min = 20, $max = 80),
So the whole return
is:
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),
];
We need to create a UsersTableSeeder
, so run:
php artisan make:seeder UsersTableSeeder
This will create /database/seeds/UsersTableSeeder.php
Add the following to the run
function:
factory(App\User::class, 5)->create();
When run, this will create 5 users, change 5 to any number of users you require.
Then we need to go to /database/seeds/DatabaseSeeder.php
and uncomment the code in the run()
function.
Finally, run php artisan db:seed
and we should have 5 new users, all with ages.
Now we’re going to create a model, controller, views and routes for our Charts page.
First run php artisan make:controller ChartController --model=Chart
Add the following to the /app/Http/Controllers/ChartController.php
:
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 code is an example of how you can do interesting things with the data in the controller, and you can specify hardcoded colours if you prefer.
Now we need to create an index.blade.php
in /resources/views/charts/
and add the following (depending on your blade setup and layout - this is an example):
Finally in /routes/web.php
we need to add the following: Route::get('/charts', 'ChartController@index')->name('charts');
Now go to your-project-name.test/charts and you should see something like the following:
You can check out the Chart.js docs for further information on customising your charts but hopefully this gives you a starting point to understand the basics of charts and graphs in Laravel.
Originally published at https://welcm.uk.