Pie Chart Integration with CodeIgniter 4 – HighCharts Js

Share this Article
Reading Time: 7 minutes

Inside this article, we will see the concept of Pie Chart Integration with CodeIgniter 4. This article will be step by step graph integration.

Pie chart represents the information in very graphical view which provides the complete idea about data. We will use jQuery Highcharts to add Pie chart into CodeIgniter 4 application.

To Learn about Bar Chart Integration in CodeIgniter 4 using jQuery Highchart, Click here.

Learn More –

Note*: For this article, CodeIgniter v4.1 setup has been installed. May be when you are seeing, version will be updated. CodeIgniter 4.x still is in development mode.

Let’s get started.

Download & Install CodeIgniter 4 Setup

We need to download & install CodeIgniter 4 application setup to system.

To set application we have multiple options to proceed.

Here are the following ways to download and install CodeIgniter 4 –

  • Manual Download
  • Composer Installation
  • Clone Github repository of CodeIgniter 4

Complete introduction of CodeIgniter 4 basics – Click here to go. After going through this article you can easily download & install setup.

Here is the command to install via composer –

$ composer create-project codeigniter4/appstarter codeigniter-4

Assuming you have successfully installed application into your local system.

Turn Development Mode On

When we install CodeIgniter 4, we have env file at root. To use the environment variables means using variables at global scope we need to do env to .env

Open project in terminal

$ cp env .env

Above command will create a copy of env file to .env file. Now we are ready to use environment variables.

CodeIgniter starts up in production mode by default. Let’s do it in development mode. So that while working if we get any error then error will show up.

# CI_ENVIRONMENT = production

 // Do it to 
CI_ENVIRONMENT = development

Now application is in development mode.

Create Database & Table in Application

To create a database, either we can create via Manual tool of PhpMyadmin or by means of a mysql command.

CREATE DATABASE codeigniter4_app;

Next, we need a table. That table will be responsible to store data. Let’s create table with some columns.

CREATE TABLE `browser_stats` (
 `name` varchar(30) NOT NULL,
 `total_usage` float NOT NULL,

Successfully, we have created a database and a table. Let’s connect with the application.

Database Connectivity to Application

Open .env file from project root. Search for DATABASE. You should see the connection environment variables.

Let’s set the value for those to connect with database.

 database.default.hostname = localhost
 database.default.database = codeigniter4_app
 database.default.username = root
 database.default.password = root
 database.default.DBDriver = MySQLi

Now, database successfully connected with application.

Import Test Data to Table

Here, we have a simple script to insert some test values into table. Copy code and execute inside created database.

-- Dumping data for table `browser_stats`

INSERT INTO `browser_stats` (`id`, `name`, `total_usage`) VALUES
(1, 'Chrome', 64.02),
(2, 'Firefox', 12.55),
(3, 'IE', 8.47),
(4, 'Safari', 6.08),
(5, 'Edge', 4.29),
(6, 'Others', 4.59);

Create Model

Open project into terminal and run this spark command to create model.

$ php spark make:model Browser --suffix

It will create BrowserModel.php at /app/Models folder.

Open BrowserModel.php and write this code.


namespace App\Models;

use CodeIgniter\Model;

class BrowserModel extends Model
	protected $DBGroup              = 'default';
	protected $table                = 'browser_stats';
	protected $primaryKey           = 'id';
	protected $useAutoIncrement     = true;
	protected $insertID             = 0;
	protected $returnType           = 'array';
	protected $useSoftDelete        = false;
	protected $protectFields        = true;
	protected $allowedFields        = [

	// Dates
	protected $useTimestamps        = false;
	protected $dateFormat           = 'datetime';
	protected $createdField         = 'created_at';
	protected $updatedField         = 'updated_at';
	protected $deletedField         = 'deleted_at';

	// Validation
	protected $validationRules      = [];
	protected $validationMessages   = [];
	protected $skipValidation       = false;
	protected $cleanValidationRules = true;

	// Callbacks
	protected $allowCallbacks       = true;
	protected $beforeInsert         = [];
	protected $afterInsert          = [];
	protected $beforeUpdate         = [];
	protected $afterUpdate          = [];
	protected $beforeFind           = [];
	protected $afterFind            = [];
	protected $beforeDelete         = [];
	protected $afterDelete          = [];

Create Route

Open Routes.php from /app/Config folder. Add this route into it.


$routes->get("browser-usage", "BrowserController::index");

Create Controller

Back to terminal and run this spark command to create application controller.

$ php spark make:controller Browser --suffix

It will create BrowserController.php file at /app/Controllers folder.


namespace App\Controllers;

use App\Controllers\BaseController;
use App\Models\BrowserModel;

class BrowserController extends BaseController
	public function index()
		$object = new BrowserModel();

		$browsers = $object->findAll();

		$dataPoints = [];

		foreach ($browsers as $browser) {
			$dataPoints[] = [
				"name" => $browser['name'],
				"y" => floatval($browser['total_usage'])

		return view("pie-chart", [
			"data" => json_encode($dataPoints)

Create View File & Render

Next, create a view file with name pie-chart.php at /app/Views folder. Open pie-chart.php and write this following code into it.

<!DOCTYPE html>
<html lang="en">

    <title>Pie Chart Integration in CodeIgniter 4</title>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/css/bootstrap.min.css">
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
    <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/js/bootstrap.min.js"></script>


    <div class="container">
        <h2 style="text-align: center;">Pie Chart Integration in CodeIgniter 4</h2>
        <div class="panel panel-primary">
            <div class="panel-heading">Pie Chart Integration in CodeIgniter 4</div>
            <div class="panel-body">
                <div id="pie-chart"></div>

    <script src="https://code.highcharts.com/highcharts.js"></script>
    <script src="https://code.highcharts.com/modules/exporting.js"></script>
    <script src="https://code.highcharts.com/modules/export-data.js"></script>
    <script src="https://code.highcharts.com/modules/accessibility.js"></script>
        $(function() {
            Highcharts.chart('pie-chart', {
                chart: {
                    plotBackgroundColor: null,
                    plotBorderWidth: null,
                    plotShadow: false,
                    type: 'pie'
                title: {
                    text: 'Browser Usage World wide'
                tooltip: {
                    pointFormat: '{series.name}: <b>{point.percentage:.1f}%</b>'
                accessibility: {
                    point: {
                        valueSuffix: '%'
                plotOptions: {
                    pie: {
                        allowPointSelect: true,
                        cursor: 'pointer',
                        dataLabels: {
                            enabled: true,
                            format: '<b>{point.name}</b>: {point.percentage:.1f} %'
                series: [{
                    name: 'Browsers',
                    colorByPoint: true,
                    data: <?= $data ?>


Application Testing

Start development server:

$ php spark serve

URL: http://localhost:8080/pie-chart

We hope this article helped you to learn Pie Chart Integration with CodeIgniter 4 Tutorial in a very detailed way.

Learn about Line Chart Integration in CodeIgniter 4, Click here.

If you liked this article, then please subscribe to our YouTube Channel for PHP & it’s framework, WordPress, Node Js video tutorials. You can also find us on Twitter and Facebook.

Find More on CodeIgniter 4 here