Laravel 13 - Create Bar, Line & Pie Charts Using Laravel Charts.

Touseef Afridi
13 Oct 26

Laravel 13 - Create Bar, Line & Pie Charts Using Laravel Charts.

In this tutorial, we will learn how to create interactive charts in Laravel 13 using the LaravelDaily Charts package, configure chart options, visualize database data, and display dynamic bar, line, and pie charts with Chart.js.

Quick Overview

This guide walks you through creating charts in a Laravel 13 application using the laraveldaily/laravel-charts package. You’ll learn how to install and configure the package, generate sample user data with a database seeder, and build a controller to visualize monthly user registrations. The tutorial covers setting up routes, creating a Blade view, and displaying charts with Chart.js. You’ll also learn how to customize chart types, including bar, line, and pie charts, to present your application data in different ways. By the end, you’ll have a working Laravel 13 application with interactive data visualizations and a clear understanding of how to adapt the chart configuration to your needs.

Step # 1: Set Up a New Laravel 13 Project.

Begin by creating a new Laravel 13 application named charts. We’ll use the Laravel Installer to generate the project. Before proceeding, ensure Composer is installed and working correctly on your system. If the Laravel Installer is not available, install it globally with the following command.
composer global require laravel/installer
Once the installation finishes, create the Laravel application by running this command.
laravel new charts
Laravel will guide you through several setup choices during project creation. Configure them as follows.
  • Starter Kit: Select No to start with a clean application without pre-built authentication or starter scaffolding.
  • Frontend Stack: Choose Blade to use Laravel’s built-in templating engine for the interface.
  • Boost Features: Accept the default selection by pressing Enter.
  • Boost Integrations: Keep the default selection and press Enter.
  • AI Agents: Select Amp when prompted to configure the AI agent.

After completing these selections, Laravel will create the charts project with Blade as the frontend and the chosen Boost and AI agent configuration.

Step # 2: Navigate to the Laravel Project Directory.

After creating the application, open your preferred terminal, such as Command Prompt, PowerShell, Git Bash, or the VS Code integrated terminal. Navigate to the charts project folder by running the following command.
cd charts
Once you are inside the project directory, you can execute Laravel Artisan commands, manage Composer dependencies, and install the packages required for your application.

Step # 3: Install the Laravel Charts Package.

To create charts in your Laravel application, install the laraveldaily/laravel-charts package using Composer. Run the following command in your terminal.
composer require laraveldaily/laravel-charts
This package makes it easier to visualize data in Laravel applications without manually building charts from scratch. It supports bar, line, and pie charts and allows you to group records by dates, string fields, or Eloquent relationships. You can use these features to analyze user registrations, track trends over time, and compare data across different categories. Chart configurations can also be customized to suit the requirements of your application.

Step # 4: Seed the Database with Sample Users.

To display meaningful data in the chart, let’s create 50 sample users with different registration dates. First, generate a new seeder by running the following Artisan command.
php artisan make:seeder UserSeeder
Next, open database/seeders/UserSeeder.php and replace its contents with the following code.
<?php
namespace Database\Seeders;
use App\Models\User;
use Illuminate\Database\Seeder;
class UserSeeder extends Seeder
{
    public function run(): void
    {
        // Create 50 users using the User factory.
        User::factory()->count(50)->create()->each(function ($user) {
            // Generate a random date within the past 12 months.
            $date = fake()->dateTimeBetween('-12 months', 'now');
            // Assign the same date to both timestamps
            // so each user's registration date stays consistent.
            $user->forceFill([
                'created_at' => $date,
                'updated_at' => $date,
            ])->save();
        });
    }
}
This seeder uses Laravel’s built-in User factory to generate 50 sample records and assigns each user a random registration date within the last 12 months. Both created_at and updated_at are set to the same date so the records have consistent timestamps. Finally, execute the seeder to insert the sample users into your database.
php artisan db:seed --class=UserSeeder
After running the command, 50 sample users will be added to your database, each with a randomly assigned registration date from the past 12 months.

Step # 5: Create the Chart Controller.

Create a controller to configure the chart and prepare the user registration data for display. Run the following Artisan command in your terminal.
php artisan make:controller ChartController
Next, open app/Http/Controllers/ChartController.php and replace its contents with the following code.
<?php
namespace App\Http\Controllers;
use LaravelDaily\LaravelCharts\Classes\LaravelChart;
class ChartController extends Controller
{
    public function index()
    {
        // Define the chart configuration options.
        $chart_options = [
            'chart_title' => 'Users Registered by Month',
            'chart_type' => 'bar',
            'report_type' => 'group_by_date',
            'model' => 'App\\Models\\User',
            'group_by_field' => 'created_at',
            'group_by_period' => 'month',
            'continuous_time' => false,
        ];
        // Create a chart instance using the defined options.
        $chart1 = new LaravelChart($chart_options);
        // Pass the chart instance to the dashboard view.
        return view('dashboard', compact('chart1'));
    }
}
The LaravelChart class uses these options to generate a monthly user registration chart. The chart_title defines the chart heading, while chart_type selects the bar format. The model identifies the User model, and group_by_field specifies the created_at column. Setting group_by_period to month groups registrations by month, while continuous_time set to false allows the chart to use the package’s regular date grouping. Finally, compact('chart1') passes the configured chart object to the dashboard Blade view for rendering.

Step # 6: Define the Chart Route.

To make the chart accessible through your browser, open routes/web.php and register a route that points to the index() method of ChartController.
use Illuminate\Support\Facades\Route;
use App\Http\Controllers\ChartController;
Route::get('/', [ChartController::class, 'index']);
This route maps the application’s homepage (/) to the index() method of ChartController, allowing users to access the monthly user registration chart directly from the browser.

Step # 7: Create the Blade View for the Chart.

Next, create a new Blade file at resources/views/dashboard.blade.php. This view will provide the page layout and display the monthly user registration chart. Add the following code to the file.
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Code Shotcut - Laravel 13 Charts</title>
    <script src="https://cdn.tailwindcss.com"></script>
    <script src="https://unpkg.com/lucide@latest"></script>
</head>
<body class="min-h-screen bg-gray-100 text-gray-900">
    <div class="min-h-screen flex flex-col">
        <!-- Header -->
        <header class="border-b border-gray-200 bg-white">
            <div class="max-w-6xl mx-auto px-5 py-3 flex items-center justify-between">
                <div class="flex items-center gap-3">
                    <div class="w-9 h-9 rounded-lg bg-indigo-50 border border-indigo-100 flex items-center justify-center text-indigo-600">
                        <i data-lucide="chart-no-axes-combined" class="w-5 h-5"></i>
                    </div>
                    <div>
                        <h1 class="text-lg font-bold tracking-tight">
                            Code Shotcut
                        </h1>
                        <p class="text-xs text-gray-500">
                            Laravel Charts
                        </p>
                    </div>
                </div>
                <div class="hidden sm:flex items-center gap-2 text-xs text-gray-500">
                    <span class="w-2 h-2 rounded-full bg-emerald-500"></span>
                    Analytics Overview
                </div>
            </div>
        </header>
        <!-- Main Content -->
        <main class="flex-1 px-4 py-4 sm:px-6 sm:py-5">
            <div class="max-w-6xl mx-auto">
                <div class="mb-4">
                    <h2 class="text-2xl sm:text-3xl font-bold tracking-tight">
                        Registration Statistics
                    </h2>
                    <p class="mt-1 text-sm text-gray-600">
                        View monthly user registration data and explore registration trends over time.
                    </p>
                </div>
                <!-- Chart Card -->
                <section class="rounded-xl border border-gray-200 bg-white p-4 sm:p-5 shadow-sm">
                    <div class="flex items-center justify-between gap-3 mb-3">
                        <div>
                            <!-- Display the chart title defined in the controller. -->
                            <h3 class="text-lg font-semibold">
                                {{ $chart1->options['chart_title'] }}
                            </h3>
                            <p class="mt-0.5 text-xs text-gray-500">
                                User registration activity
                            </p>
                        </div>
                        <div class="hidden sm:inline-flex items-center gap-1.5 text-xs text-gray-500">
                            <i data-lucide="calendar-days" class="w-4 h-4"></i>
                            Monthly Report
                        </div>
                    </div>
                    <!-- Render the chart's HTML markup generated by Laravel Charts. -->
                    <div class="w-full overflow-hidden">
                        {!! $chart1->renderHtml() !!}
                    </div>
                </section>
                <section class="mt-4 rounded-xl border border-indigo-100 bg-white p-4 sm:p-5 shadow-sm">
                    <div class="flex flex-col gap-3 sm:flex-row sm:items-center sm:justify-between">
                        <div class="max-w-2xl">
                            <div class="inline-flex items-center gap-1.5 text-xs font-semibold text-indigo-600">
                                <i data-lucide="graduation-cap" class="w-4 h-4"></i>
                                Learn More
                            </div>
                            <h3 class="mt-1.5 text-lg font-bold tracking-tight">
                                Build More with Code Shotcut
                            </h3>
                            <p class="mt-1 text-sm leading-5 text-gray-600">
                                Explore practical Laravel tutorials, PHP development guides,
                                useful packages, integrations, and real-world coding examples
                                on our website and YouTube channel.
                            </p>
                        </div>
                        <div class="flex flex-col xs:flex-row sm:flex-col lg:flex-row gap-2 shrink-0">
                            <a
                                href="https://codeshotcut.com/"
                                target="_blank"
                                rel="noopener noreferrer"
                                class="inline-flex items-center justify-center gap-2 rounded-lg bg-indigo-600 px-4 py-2.5 text-sm font-semibold text-white transition hover:bg-indigo-700"
                            >
                                <i data-lucide="external-link" class="w-4 h-4"></i>
                                Visit Website
                            </a>
                            <a
                                href="https://www.youtube.com/@CodeShotcut"
                                target="_blank"
                                rel="noopener noreferrer"
                                class="inline-flex items-center justify-center gap-2 rounded-lg border border-gray-200 bg-white px-4 py-2.5 text-sm font-semibold text-gray-700 transition hover:border-red-200 hover:bg-red-50 hover:text-red-600"
                            >
                                <i data-lucide="youtube" class="w-4 h-4"></i>
                                Watch on YouTube
                            </a>
                        </div>
                    </div>
                </section>
            </div>
        </main>
        <!-- Footer -->
        <footer class="border-t border-gray-200 bg-white">
            <div class="max-w-6xl mx-auto px-5 py-2.5 flex flex-col sm:flex-row items-center justify-between gap-1.5">
                <p class="text-xs text-gray-500">
                    Built with Laravel 13, LaravelDaily Charts & Tailwind CSS
                </p>
                <a
                    href="https://codeshotcut.com/"
                    target="_blank"
                    rel="noopener noreferrer"
                    class="text-xs font-medium text-indigo-600 hover:text-indigo-800"
                >
                    More tutorials at Code Shotcut
                </a>
            </div>
        </footer>
    </div>
    <!-- Load the Chart.js library and initialize the chart. -->
    {!! $chart1->renderChartJsLibrary() !!}
    {!! $chart1->renderJs() !!}
    <!-- Initialize the Lucide icons used throughout the page. -->
    <script>
        lucide.createIcons();
    </script>
</body>
</html>
The view displays the monthly user registration chart using the configuration defined in ChartController. The chart title is generated dynamically from $chart1, while renderHtml(), renderChartJsLibrary(), and renderJs() handle the chart markup, Chart.js library, and JavaScript initialization, respectively. With these components in place, the chart is ready to display the registered users grouped by month.

Step # 8: Run and Test the Laravel Chart.

Start the Laravel development server by running the following command in your terminal.
php artisan serve
Open http://127.0.0.1:8000 in your browser to view the chart. You should see the monthly user registration data displayed as a bar chart, with users grouped by their created_at dates.

The chart is now ready to display your monthly user registration data, making it easy to visualize registration trends over the past 12 months.
Explore Other Chart Types:
The LaravelDaily Charts package also supports line charts and pie charts, giving you more options to visualize your application data. A line chart is useful for identifying trends in user registrations over time, while a pie chart represents data as slices for comparing different categories.

Line Chart:

To display monthly user registrations as a line chart, open ChartController.php and change the chart_type option to
'chart_type' => 'line',
Save the changes, then refresh your browser at http://127.0.0.1:8000 to view the line chart.

Pie Chart:
The package also provides a pie chart option. To display your chart as a pie chart, change the same option to.
'chart_type' => 'pie',
Save the changes and refresh the browser again to see the pie chart.

In both examples, keep the remaining chart configuration unchanged. You can switch between bar, line, and pie charts by updating the chart_type value to suit your data visualization needs.

Conclusion

By following this guide, you’ve learned how to integrate the LaravelDaily Charts package into a Laravel 13 application. You created a new project, installed the package, seeded the database with sample users, configured a chart controller, defined a route, and built a Blade view to display monthly user registrations. You also explored how to display the same data using bar, line, and pie charts by changing the chart configuration. With these options, you can visualize database records and adapt charts to different reporting needs without manually building the entire chart implementation.
For more configuration options and advanced features, visit the official LaravelDaily Charts documentation: https://github.com/LaravelDaily/laravel-charts.
Share this with friends!


"Give this post some love and slap that 💖 button as if it owes you money! 💸😄"
0

0 Comments

To engage in commentary, kindly proceed by logging in or registering