Codeigniter 4 Morris Bar & Stacked Chart Examples

Codeigniter 4 Morris Bar, In this tutorial, we’ll show you how to create Morris bar and stacked charts in Codeigniter 4. Specifically, we’ll demonstrate how to get data from a MySQL database for the current week and display it in charts.

You’ll learn how to get data from MySQL day by day for the current week and year, and then display that data using Morris stacked and bar charts in your Codeigniter 4 app. We’ll guide you through the process step by step.

To implement the bar chart and stacked bar chart in Codeigniter 4, we’ll be using Morris Chart JS. We’ll also show you how to fetch days wise records from the MySQL database and display them on the charts.

How To Morris Stacked and Bar Chart In Codeigniter 4 App

  • Download Codeigniter 4 Project
  • Basic Configurations
  • Create Table in Database
  • Setup Database Credentials
  • Create Controller
  • Create View
  • Create Route
  • Start Development Server

Step 1: Download Codeigniter 4 Project

Now, let’s get started by downloading the latest version of CodeIgniter 4. To do this, go to this link https://codeigniter.com/download and download the fresh new setup. After downloading, extract the setup and place it in your local system’s xampp/htdocs/ directory. You can also change the folder name from “demo” to any name of your choice.

Step 2: Basic Configurations

Next, we need to configure some basic settings in the app/config/app.php file. To do this, open the file in a text editor by navigating to the application/config/ directory.

Once you have opened the file, you need to set the Base URL by adding the following code:

public $baseURL = 'http://localhost:8080';
To
public $baseURL = 'http://localhost/demo/';

Step 3: Create Table in Database

To make a bar and stacked chart work in codeigniter 4, you have to follow this step: create a table in your database and insert some data into it. To do this, go to your phpmyadmin panel and run this sql query:

CREATE TABLE users (
    id int(11) NOT NULL AUTO_INCREMENT COMMENT 'Primary Key',
    name varchar(100) NOT NULL COMMENT 'Name',
    email varchar(255) NOT NULL COMMENT 'Email Address',
    contact_no varchar(50) NOT NULL COMMENT 'Contact No',
    created_at varchar(20) NOT NULL COMMENT 'Created date',
    PRIMARY KEY (id)
  ) ENGINE=InnoDB DEFAULT CHARSET=latin1 COMMENT='datatable demo table' AUTO_INCREMENT=1;
 
  INSERT INTO users (id, name, email, contact_no, created_at) VALUES
  (1, 'Team', 'info@torqueprogramming.co.in', '9000000001', '2023-01-01'),
  (2, 'Admin', 'admin@torqueprogramming.co.in', '9000000002', '2023-01-02'),
  (3, 'User', 'user@torqueprogramming.co.in', '9000000003', '2023-01-03'),
  (4, 'Editor', 'editor@torqueprogramming.co.in', '9000000004', '2023-01-04'),
  (5, 'Writer', 'writer@torqueprogramming.co.in', '9000000005', '2023-01-05'),
  (6, 'Contact', 'contact@torqueprogramming.co.in', '9000000006', '2023-01-06'),
  (7, 'Manager', 'manager@torqueprogramming.co.in', '9000000007', '2023-01-07'),
  (8, 'John', 'john@torqueprogramming.co.in', '9000000055', '2023-01-08'),
  (9, 'Merry', 'merry@torqueprogramming.co.in', '9000000088', '2023-01-09'),
  (10, 'Keliv', 'kelvin@torqueprogramming.co.in', '9000550088', '2023-01-10'),
  (11, 'Herry', 'herry@torqueprogramming.co.in', '9050550088', '2023-01-11'),
  (12, 'Mark', 'mark@torqueprogramming.co.in', '9050550998', '2023-01-12');

Step 4: Setup Database Credentials

To connect your project to the database, follow this step: go to app/Config/Database.php and open the database.php file in a text editor. Once you have the file open, set up your database credentials like the example below.

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

Step 5: Create Controller

To follow this step, go to app/Controllers and create a new controller called MorrisChart.php. Then, add the following methods to it:

<?php namespace App\Controllers;
use CodeIgniter\Controller;
use CodeIgniter\HTTP\RequestInterface;
 
 
class MorrisChart extends Controller
{
 
    public function index() {
 
        $db      = \Config\Database::connect();
        $builder = $db->table('users');   
 
        $query = $builder->query("SELECT DAYNAME(created_at) as y, COUNT(id) as a  FROM users WHERE date(created_at) > DATE_SUB(NOW(), INTERVAL 1 WEEK) AND MONTH(created_at) = '" . date('m') . "' AND YEAR(created_at) = '" . date('Y') . "' GROUP BY DAYNAME(created_at)");
 
      $data['day_wise'] = $query->getResult();
         
        return view('home',$data);
    }
 
}

Step 6: Create View

To complete this step, create a new view file called home.php. Then, update the code in the file with the following:

<head>
    <meta charset="utf-8" />
    <title>Morris.js Bar and Stacked Chart With Codeigniter - torqueprogramming.co.in</title>
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css" integrity="sha384-Gn5384xqQ1aoWXA+058RXPxPg6fy4IWvTNh0E263XmFcJlSAwiGgFAW/dAiS6JXm" crossorigin="anonymous" />
    <script src="https://code.jquery.com/jquery-3.3.1.min.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/raphael/2.1.2/raphael-min.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/morris.js/0.5.0/morris.min.js"></script>
</head>
<body>
    <h3 class="text-primary text-center">
        Morris charts with Codeigniter
    </h3>
    <div class"row">
    <div class="col-sm-6 text-center">
        <label class="label label-success">Bar Chart</label>
        <div id="bar-chart"></div>
    </div>
    <div class="col-sm-6 text-center">
        <label class="label label-success">Bar stacked</label>
        <div id="stacked"></div>
    </div>
</body>

Implement Javascript code

To display the data on morris bar chart, you need to implement some JavaScript code. To do this, simply update the code inside the script tag after the closing of the body tag.

<script>
    var serries = JSON.parse(`<?php echo $day_wise; ?>`);
    console.log(serries);
    var data = serries,
        config = {
            data: data,
            xkey: "y",
            ykeys: ["a"],
            labels: ["This Week Total Registered Users"],
            fillOpacity: 0.6,
            hideHover: "auto",
            behaveLikeLine: true,
            resize: true,
            pointFillColors: ["#ffffff"],
            pointStrokeColors: ["black"],
            lineColors: ["gray", "red"],
        };

    //for mories bar chart
    config.element = "bar-chart";
    Morris.Bar(config);

    //for stacked bar chart
    config.element = "stacked";
    config.stacked = true;
    Morris.Bar(config);
</script>

Step 7: Create Route

Now, we need to create a route that renders the table into the view. To do this, open the app/Config/Routes.php file and add the following code:

$routes->get('/', 'MorrisChart::index');

Step 8: Start Development Server

Finally, we are ready to start the development server. To do this, open your terminal and execute the following command:

php spark serve

then, Go to the browser and hit below the URL:

http://localhost:8080

You May Also Like

  1. CodeIgniter 4 Server Side DataTable Example
  2. Codeigniter 4 Google Map Multiple Markers Example
  3. Codeigniter 4 Get Latitude and Longitude From Address
  4. Country State City Dependent Dropdown in Codeigniter 4
  5. Codeigniter 4 Import Data to Excel/CSV File From MySQL Database
  6. Codeigniter 4 Dynamic Dependent Dropdown with Ajax
  7. Codeigniter 4 Autocomplete Textbox From Database using Typeahead JS
  8. Codeigniter 4 PDF Generator Tutorial Example
  9. Crop and Save Image using jQuery Coppie in Codeigniter 4

Leave a Reply

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