How to Create Dynamic Multi Line Chart in Laravel 11

Hello, laravel web developers! In this article, we'll see how to create a dynamic multi line chart in laravel 11. In laravel 11, we'll use echart library to display dynamic multi line charts. A multi-line chart is a basic line chart with one or more additional lines that represent comparison trends.

Using this chart, you can easily compare the position, performance, or rankings of multiple observations to each other rather than the actual values themselves.

Laravel 11 Create Dynamic Multi Line Chart

laravel 11 create dynamic multi line chart

 

Step 1: Install Laravel 11 Application

In this step, we'll install the laravel 11 application using the following command.

composer create-project --prefer-dist laravel/laravel multi-line-chart

 

Step 2: Configure Database

Next, we'll Configure your .env file with your database credentials.

DB_CONNECTION=mysql
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE=your_database_name
DB_USERNAME=your_database_user
DB_PASSWORD=your_database_password

Then, create a migration using the following command.

php artisan make:migration create_data_points_table --create=data_points

Migration:

Schema::create('data_points', function (Blueprint $table) {
    $table->id();
    $table->string('name');
    $table->integer('year');
    $table->integer('value');
    $table->timestamps();
});

Then, run the migrate the table into the database using the following command.

php artisan migrate

 

Step 3: Create a Model and Controller

Next, we'll create a model and controller using the following command.

php artisan make:model DataPoint

Create a controller.

php artisan make:controller ChartController

app/Http/Controllers/ChartController.php

use App\Http\Controllers\Controller;
use Illuminate\Support\Facades\DB;
use App\Models\DataPoint;

class ChartController extends Controller
{
    public function index()
    {
        $data = DataPoint::get();
        $formattedData = $this->formatData($data);
        return view('chart', compact('formattedData'));
    }

    private function formatData($data)
    {
        $result = [];
        foreach ($data as $item) {
            $result[$item->name][] = $item->value;
        }
        return $result;
    }
}

 

Step 4: Define Route

Now, Define a route to the web.php file.

routes/web.php

use App\Http\Controllers\ChartController;

Route::get('/', [ChartController::class, 'index']);

 

Step 5: Create the Blade View

Next, we'll create a blade view to display the dynamic chart.

resources/views/chart.blade.php

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="utf-8">
    <title>Dynamic Multi Line Chart in Laravel 11 - Techsolutionstuff</title>
    <style>
        * {
            margin: 0;
            padding: 0;
        }
        #chart-container {
            position: relative;
            height: 100vh;
            overflow: hidden;
        }
    </style>
</head>
<body>
    <div id="chart-container"></div>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.7.1/jquery.min.js"></script>
    <script src="https://fastly.jsdelivr.net/npm/echarts@5.5.1/dist/echarts.min.js"></script>
    <script>
        var dom = document.getElementById('chart-container');
        var myChart = echarts.init(dom, null, {
            renderer: 'canvas',
            useDirtyRect: false
        });
        var app = {};

        var option;

        const names = [
            'Orange',
            'Tomato',
            'Apple',
        ];
        const years = ['2001', '2002', '2003', '2004', '2005', '2006'];
        
        const formattedData = @json($formattedData);
        
        const generateSeriesList = () => {
            const seriesList = [];
            for (const [name, data] of Object.entries(formattedData)) {
                const series = {
                    name,
                    symbolSize: 20,
                    type: 'line',
                    smooth: true,
                    emphasis: {
                        focus: 'series'
                    },
                    endLabel: {
                        show: true,
                        formatter: '{a}',
                        distance: 20
                    },
                    lineStyle: {
                        width: 4
                    },
                    data
                };
                seriesList.push(series);
            }
            return seriesList;
        };

        option = {
            title: {
                text: 'Multi Line Chart'
            },
            tooltip: {
                trigger: 'item'
            },
            grid: {
                left: 30,
                right: 110,
                bottom: 30,
                containLabel: true
            },
            toolbox: {
                feature: {
                    saveAsImage: {}
                }
            },
            xAxis: {
                type: 'category',
                splitLine: {
                    show: true
                },
                axisLabel: {
                    margin: 30,
                    fontSize: 16
                },
                boundaryGap: false,
                data: years
            },
            yAxis: {
                type: 'value',
                axisLabel: {
                    margin: 30,
                    fontSize: 16,
                    formatter: '#{value}'
                },
                inverse: true,
                interval: 1,
                min: 1,
                max: names.length
            },
            series: generateSeriesList()
        };

        if (option && typeof option === 'object') {
            myChart.setOption(option);
        }

        window.addEventListener('resize', myChart.resize);
    </script>
</body>
</html>

 

Step 6: Create Seeder

Next, we'll create a seeder for sample data using the following command.

php artisan make:seeder DataPointsSeeder

database/seeders/DataPointsSeeder.php

use Illuminate\Database\Seeder;
use Illuminate\Support\Facades\DB;

class DataPointsSeeder extends Seeder
{
    public function run()
    {
        $names = ['Orange', 'Tomato', 'Apple'];
        $years = range(2001, 2006);

        foreach ($years as $year) {
            foreach ($names as $name) {
                DB::table('data_points')->insert([
                    'name' => $name,
                    'year' => $year,
                    'value' => rand(1, 3),
                    'created_at' => now(),
                    'updated_at' => now(),
                ]);
            }
        }
    }
}

Run the seeder using the following command.

php artisan db:seed --class=DataPointsSeeder

 

Step 7: Run the Laravel 11 Application

Now, run the laravel 11 application using the following command.

php artisan serve

 


You might also like:

techsolutionstuff

Techsolutionstuff | The Complete Guide

I'm a software engineer and the founder of techsolutionstuff.com. Hailing from India, I craft articles, tutorials, tricks, and tips to aid developers. Explore Laravel, PHP, MySQL, jQuery, Bootstrap, Node.js, Vue.js, and AngularJS in our tech stack.

RECOMMENDED POSTS

FEATURE POSTS