Code your dreams into reality.
Every line of code is a step towards a better future.
Embrace the bugs, they make you a better debugger.

CodeIgniter 4 Bar Chart Tutorial

Last Updated on August 8, 2024 by

The Chart.js library is a third-party JavaScript library that developers can use to create bar charts, line charts, graph charts, pie charts, etc, in applications.

Let’s start creating bar charts and displaying dynamic data from database in CodeIgniter 4 application:

Step 1: Set Up Database

Run the following command to create a database and a table:

CREATE DATABASE ci4_db;

USE ci4_db;

CREATE TABLE sales (
    id INT AUTO_INCREMENT PRIMARY KEY,
    product VARCHAR(255) NOT NULL,
    quantity INT NOT NULL
);

INSERT INTO sales (product, quantity) VALUES ('Product A', 30), ('Product B', 50), ('Product C', 20), ('Product D', 40);

Step 2: Configure Database

Edit .env file, and configure database in it:

database.default.hostname = localhost
database.default.database = ci4_db
database.default.username = your_username
database.default.password = your_password
database.default.DBDriver = MySQLi

Step 3: Create the Model

Go to app/models directory and create SalesModel.php model file to interact to database table:

// app/Models/SalesModel.php
namespace App\Models;

use CodeIgniter\Model;

class SalesModel extends Model
{
    protected $table = 'sales';
    protected $primaryKey = 'id';
    protected $allowedFields = ['product', 'quantity'];
}

Step 4: Create the Controller

Go to app/controllers directory and create a controller file named Sales.php to fetch the data and load the view:

// app/Controllers/Sales.php
namespace App\Controllers;

use App\Models\SalesModel;

class Sales extends BaseController
{
    public function index()
    {
        return view('sales_chart');
    }

    public function getSalesData()
    {
        $model = new SalesModel();
        $sales = $model->findAll();

        $data = [
            'labels' => [],
            'data' => []
        ];

        foreach ($sales as $sale) {
            $data['labels'][] = $sale['product'];
            $data['data'][] = $sale['quantity'];
        }

        return $this->response->setJSON($data);
    }
}

Step 5: Create the View

Go to app/views directory, create a view file named sales_chart.php that includes Chart.js and sets up the bar chart:

<!-- app/Views/sales_chart.php -->
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Sales Bar Chart</title>
    <script src="https://cdn.jsdelivr.net/npm/chart.js"></script>
</head>
<body>
    <div class="container">
        <h1>Sales Bar Chart</h1>
        <canvas id="salesChart"></canvas>
    </div>
</body>
</html>

Step 6: Define Routes

Edit app/Config/Routes.php file, and define routes in it:

// app/Config/Routes.php
$routes->get('sales', 'Sales::index');
$routes->get('sales/getSalesData', 'Sales::getSalesData');

Step 7: Test the Application

  1. Start the development server by running the command: php spark serve
  2. Open your browser and type url http://localhost:8080/sales on browser to test this application.

Leave a Comment