Codeigniter 4 Morris Stacked & Bar Chart Tutorial Example

Last updated on: by Digamber

Do you struggle to add morris bar and stacked charts in Codeigniter 4 application? We will tell you how profoundly integrate stacked charts in Codeigniter.

Not only but also, we will show how to write and properly use Codeigniter SQL queries to filter the data and dynamically retrieve the sales day-wise data from the database and display it in the stacked and bar charts.

This Codeigniter 4 morris chart example is for novice programmers who want to amplify their understanding and mastery over charts integration in PHP Codeigniter.

Also, learn how to implement javascript morris stacked and bar charts in the Codeigniter app with MySQL database.

How to Add Morris Stacked Chart Bar in Codeigniter 4 Application

  • Step 1: Install Codeigniter Project
  • Step 2: Connect App to Database
  • Step 3: Create Table & 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

This step is for those who haven’t downloaded the Codeigniter application. You may use either of the methods to commence the app installation process.

Install app using the direct link:

https://codeigniter.com/download

Download app using the Composer:

composer create-project codeigniter4/appstarter

Next, change the default project folder name to “my_ci_app” or anything fancy you want.

Connect App to Database

In this step, we will learn to build the codeigniter application connection with database.

Open the app/Config/Database.php, and insert 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 & Insert Data

In this section, we would request you to step inside your SQL query section and recklessly execute the following command and generate a table at the same time insert few records into 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

You have to generate a new controller template, right after that add the following code into the app/Controllers/MorrisChartController.php file.

<?php 
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 for showing charts, you need to go to app/Config/Routes.php and define the given below routes in the file.

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

Setting Up View File

Create a view file, add morris js with the required dependencies like jQuery and Raphael to view template; create charts div and define respective ids to load the charts in both the div.

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

Add code into app/Views/index.php file.

<!DOCTYPE html>
<html lang="en">
<head>
	<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="https://cdn.jsdelivr.net/npm/bootstrap@5.0.2/dist/css/bootstrap.min.css">
	<link rel="stylesheet" href="//cdnjs.cloudflare.com/ajax/libs/morris.js/0.5.1/morris.css">
</head>
<body>
	<body>
		<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>		
			<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>
			</div>
		</div>
        <!-- Add scripts -->
		<script src="//ajax.googleapis.com/ajax/libs/jquery/1.9.0/jquery.min.js"></script>
		<script src="//cdnjs.cloudflare.com/ajax/libs/raphael/2.1.0/raphael-min.js"></script>
		<script src="//cdnjs.cloudflare.com/ajax/libs/morris.js/0.5.1/morris.min.js"></script>
		<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';
			Morris.Bar(config);
			
			// Call stacked chart
			config.element = 'MorrisStakcedChart';
			config.stacked = true;
			Morris.Bar(config);
		</script>
	</body>
</html>

Run Application

In this last step, you have to open the terminal, type command to run the application.

php spark serve

You can take the help of the following url to see the morris charts in the browser.

http://localhost:8080/morris-charts

Codeigniter 4 Morris Stacked & Bar Chart Example

Conclusion

We shared a smarter way to learn about JavaScript morris charts; this is just a beginning; however, you may go to the next level and show data in bar charts and stacked charts through several other approaches.

Through this definitive guide, we always aimed to cut your efforts drastically. We have seen the pragmatic methods to integrate morris bar charts and morris stacked charts in the Codeigniter app.

positronX.io - Tamso Ma Jyotirgamaya
Digamber

A Full-stack developer with a passion to solve real world problems through functional programming.