Skip to content

All topics  /  CodeIgniter

Codeigniter 4 Morris Stacked & Bar Chart Tutorial Example

CodeIgniter ·

Teams applying “Codeigniter 4 Morris Stacked & Bar Chart Tutorial Example” in a production project can use this team workflow page to record implementation, review and debugging time, then compare that effort with tests and shipped functionality instead of treating activity as performance by itself.

Before copying the example into a live application, confirm version-specific behaviour with CodeIgniter and test it against the project’s actual database and runtime.

Hi guys,

Today i will explained Morris Stacked & Bar Chart Tutorial Example in Codeigniter 4. This example is so easy to use in Codeigniter 4.

Today i will implemented to the Morris Stacked & Bar Chart in Codeigniter. I am implemented to the seven steps to implement in stacked & bar chart in Codeigniter.

So let's start to the example.

Step 1: Install Codeigniter Project


Codeigniter Project Project install in a two ways.

https://codeigniter.com/download
or
composer create-project codeigniter4/appstarter project_name

Step 2: Connect App to 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,
    ];

Step 3: Create Table & Insert Data

Then next step to create table and insert to the few records.

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');

Step 4: 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); 
    }

 
}

Step 5: Make Route File next 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');

Step 6: 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

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 Nicesnippets.com</title>
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css">
    <link rel="stylesheet" href="//cdnjs.cloudflare.com/ajax/libs/morris.js/0.5.1/morris.css">
</head>
    <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>

Step 7: Run Application

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

php spark serve

Then next run the url in your browser.

http://localhost:8080/morris-charts

Output

Now you can check your own.