CodeIgniter 4 Morris Stacked And Bar Chart Tutorial Example

Have you ever added Morris Bar And Stacked Charts in CodeIgniter 4 App? In this tutorial, we will learn how to do so in an easy and smooth manner.

We will also get to know how to write and use CodeIgniter SQL queries to filter the data and retrieve the sales day-wise data from the database and display it in the stacked and bar charts.

With the help of this CodeIgniter example, even a novice programmer will be able to integrate the charts in PHP CodeIgniter. We will also learn how to javascript morris stacked and bar charts in the CodeIgniter app with MySQL database.


How To Add Morris Stacked Bar Chart In CodeIgniter 4 Application

Step 1- Install CodeIgniter Project

Step 2- Connect App To Database

Step 3- Create Table And Insert Data

Step 4- Make Controller File

Step 5- Make Route File

Step 6- Setting Up View File

Step 7- Run Application


Install CodeIgniter Project

In this step, we simply have to download the CodeIgniter application. We can use any of the methods for starting the installation process.

We will install the app by using the direct link:


Download the app using the Composer:

composer create-project codeigniter4/appstarter


Next is required to change the default project folder name to “my_ci_app” or any other name we want.


Connect App To Database

Here, we will learn how to build the CodeIgniter application connection with the database.

Next, we will open the app/Config/Database.php and insert the database name, username and password into the file:

public $default = [
        'DSN'      => '',
        'hostname' => 'localhost',
        'username' => 'root',
        'password' => '',
        'database' => 'codeigniter_db',
        'DBDriver' => 'MySQLi',
        'DBPrefix' => '',
        'pConnect' => false,
        'DBDebug'  => (ENVIRONMENT !== 'development'),
        'cacheOn'  => false,
        'cacheDir' => '',
        'charset'  => 'utf8',
        'DBCollat' => 'utf8_general_ci',
        'swapPre'  => '',
        'encrypt'  => false,
        'compress' => false,
        'strictOn' => false,
        'failover' => [],
        'port'     => 3306,


Create Table And Insert Data

So, in this step, we have to step inside the SQL query section and recklessly execute the command given below and generate a table at the same time. Insert few records in it:

CREATE TABLE `product` (
  `id` int(11) NOT NULL COMMENT 'Primary Key',
  `name` varchar(255) NOT NULL COMMENT 'name',
  `sell` varchar(55) NOT NULL COMMENT 'sell',    
  `created_at` varchar(30) NOT NULL COMMENT 'created at'
) ENGINE=InnoDB DEFAULT CHARSET=latin1 COMMENT='Atomic database';

INSERT INTO `product` (`id`, `name`, `sell`, `created_at`) VALUES
(1, 'Coca Cola', '5000', '2021-05-01'),
(2, 'Pepsi', '7000', '2021-05-02'),
(3, 'Coke Zero', '19000', '2021-05-03'),
(4, 'Pepsi Max', '1500', '2021-05-04'),
(5, 'Diet Coke', '19000', '2021-05-05'),
(6, 'Pepsi Light', '3000', '2021-05-06'),
(7, 'Gatorade', '22000', '2021-05-07');


Make Controller File

We will generate a new controller template, after which, we will add the given code into the app/Controllers/MorrisChartController.php file:


namespace App\Controllers;
use CodeIgniter\Controller;

class MorrisChartController extends Controller

    public function index() {
        return view('index');
    public function startChart() {
        $db = \Config\Database::connect();
        $builder = $db->table('product');

        $query = $builder->select("COUNT(id) as count, sell as s, DAYNAME(created_at) as day");
        $query = $builder->where("DAY(created_at) GROUP BY DAYNAME(created_at), s");
        $query = $builder->orderBy("s ASC, day ASC")->get();
        $data['products'] = $query->getResult();

        return view('index', $data); 


Make Route File

To make the route show charts, we will go to app/Config/Routes.php and define the following routes in the file:


$routes->get('/morris-charts', 'MorrisChartController::startChart');


Setting Up View File

In this step, we have to create a view file, add morris js with the required dependencies like j Query and Raphael to view the template; create charts div and define respective ids to load the charts in both the div.

Lastly, we will add the script tag right before the body tag; we can set various options using config object; this makes chart customization easy.

Then, we will add the code into app/Views/index.php file:

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

	<meta charset="UTF-8">
	<meta name="viewport" content="width=device-width, initial-scale=1.0">
	<title>Codeigniter Morris Stacked and Bar Charts Demo</title>
	<link rel="stylesheet" href="[email protected]/dist/css/bootstrap.min.css">
	<link rel="stylesheet" href="//">


		<div class="container">
    		<div class="mt-5">
			<h2 class="text-center mb-5">Codeigniter Morris Stacked Chart Example</h2>
				<div id="MorrisStakcedChart" style="height: 400px; width: 100%"></div>

			<div class="mt-5">
			    <h2 class="text-center mb-5">Codeigniter Morris Bar Chart Example</h2>
				<div id="MorrisBarChart" style="height: 400px; width: 100%"></div>

        <!-- Add scripts -->
		<script src="//"></script>
		<script src="//"></script>
		<script src="//"></script>
			var serries = <?php echo json_encode($products); ?>;
			var data = serries,
				config = {
					data: <?php echo json_encode($products); ?>,
					xkey: 'day',
					ykeys: ['s'],
					labels: ['Sales this week'],
					fillOpacity: 0.7,
					hideHover: 'auto',
					resize: true,
					behaveLikeLine: true,
					stacked: true,
					barColors: "455"
			// Call bar chart
			config.element = 'MorrisBarChart';
			// Call stacked chart
			config.element = 'MorrisStakcedChart';
			config.stacked = true;


Run The Application

Here, in this last step, we just have to open the terminal and type the command for running the application:

php spark serve



So friends, hope that you have learnt about JavaScript Morris Charts in quite a smart way. With the help of this, you can also go to the next level and show the data in a Bar Chart and Stacked Chart.



Leave a Reply

Your email address will not be published. Required fields are marked *