Skip to content Skip to sidebar Skip to footer

CRUD CodeIgniter 4 With Bootstrap Basic Tutorial

 

CRUD CodeIgniter 4

CRUD CodeIgniter 4 With Bootstrap Basic - This is a guide to create a CRUD (Create, Read, Update and Delete) application using the CodeIgniter 4 framework.

In this article I will create an application to show student data crud codeigniter 4. Where here is using the Linux operating system.

For server and mysql, I use xampp.

The first thing to do is to install Composer, so that packages can be downloaded easily only through the terminal.

Install Composer

The first step crud codeigniter 4 is to open a terminal and use the command:

sudo apt update
sudo apt install composer

If you wanto to install Composer 2,  please read here.

After composer is successfully installed, the next step is...

 

Install CodeIgniter

I want the codeigniter project to be in the "Documents/Project-CI4" folder. So first create a Project-CI4 folder in Document. And for our project name later is crud_basic. 

cd /Documents/Project-CI4
composer create-project codeigniter4/appstarter crud_basic

If successful you will see something like this:

neon@neon:~/Documents/Project-CI4$ composer create-project codeigniter4/appstarter crud_basic
Creating a "codeigniter4/appstarter" project at "./crud_basic"
Installing codeigniter4/appstarter (v4.1.5)
  - Downloading codeigniter4/appstarter (v4.1.5)
  - Downloading codeigniter4/appstarter (v4.1.5)
  - Installing codeigniter4/appstarter (v4.1.5): Extracting archive
Created project in /home/neon/Documents/Project-CI4/crud_basic
Loading composer repositories with package information
Updating dependencies
Lock file operations: 42 installs, 0 updates, 0 removals
  - Locking codeigniter4/framework (v4.1.5)
  - Locking doctrine/instantiator (1.4.0)
  - Locking fakerphp/faker (v1.17.0)
  - Locking kint-php/kint (3.3)
  - Locking laminas/laminas-escaper (2.9.0)
  - Locking mikey179/vfsstream (v1.6.10)
  - Locking myclabs/deep-copy (1.10.2)
  - Locking nikic/php-parser (v4.13.2)
  - Locking phar-io/manifest (2.0.3)
  - Locking phar-io/version (3.1.0)
  - Locking phpdocumentor/reflection-common (2.2.0)
  - Locking phpdocumentor/reflection-docblock (5.3.0)
  - Locking phpdocumentor/type-resolver (1.5.1)
  - Locking phpspec/prophecy (1.14.0)
  - Locking phpunit/php-code-coverage (9.2.10)
  - Locking phpunit/php-file-iterator (3.0.6)
  - Locking phpunit/php-invoker (3.1.1)
  - Locking phpunit/php-text-template (2.0.4)
  - Locking phpunit/php-timer (5.0.3)
  - Locking phpunit/phpunit (9.5.10)
  - Locking psr/container (2.0.2)
  - Locking psr/log (1.1.4)
  - Locking sebastian/cli-parser (1.0.1)
  - Locking sebastian/code-unit (1.0.8)
  - Locking sebastian/code-unit-reverse-lookup (2.0.3)
  - Locking sebastian/comparator (4.0.6)
  - Locking sebastian/complexity (2.0.2)
  - Locking sebastian/diff (4.0.4)
  - Locking sebastian/environment (5.1.3)
  - Locking sebastian/exporter (4.0.4)
  - Locking sebastian/global-state (5.0.3)
  - Locking sebastian/lines-of-code (1.0.3)
  - Locking sebastian/object-enumerator (4.0.4)
  - Locking sebastian/object-reflector (2.0.4)
  - Locking sebastian/recursion-context (4.0.4)
  - Locking sebastian/resource-operations (3.0.3)
  - Locking sebastian/type (2.3.4)
  - Locking sebastian/version (3.0.2)
  - Locking symfony/deprecation-contracts (v3.0.0)
  - Locking symfony/polyfill-ctype (v1.23.0)
  - Locking theseer/tokenizer (1.2.1)
  - Locking webmozart/assert (1.10.0)
Writing lock file
Installing dependencies from lock file (including require-dev)
Package operations: 42 installs, 0 updates, 0 removals
  - Downloading psr/log (1.1.4)
  - Downloading laminas/laminas-escaper (2.9.0)
  - Downloading kint-php/kint (3.3)
  - Downloading codeigniter4/framework (v4.1.5)
  - Downloading symfony/deprecation-contracts (v3.0.0)
  - Downloading psr/container (2.0.2)
  - Downloading fakerphp/faker (v1.17.0)
  - Downloading mikey179/vfsstream (v1.6.10)
  - Downloading symfony/polyfill-ctype (v1.23.0)
  - Downloading webmozart/assert (1.10.0)
  - Downloading phpdocumentor/reflection-common (2.2.0)
  - Downloading phpdocumentor/type-resolver (1.5.1)
  - Downloading phpdocumentor/reflection-docblock (5.3.0)
  - Downloading sebastian/version (3.0.2)
  - Downloading sebastian/type (2.3.4)
  - Downloading sebastian/resource-operations (3.0.3)
  - Downloading sebastian/recursion-context (4.0.4)
  - Downloading sebastian/object-reflector (2.0.4)
  - Downloading sebastian/object-enumerator (4.0.4)
  - Downloading sebastian/global-state (5.0.3)
  - Downloading sebastian/exporter (4.0.4)
  - Downloading sebastian/environment (5.1.3)
  - Downloading sebastian/diff (4.0.4)
  - Downloading sebastian/comparator (4.0.6)
  - Downloading sebastian/code-unit (1.0.8)
  - Downloading sebastian/cli-parser (1.0.1)
  - Downloading phpunit/php-timer (5.0.3)
  - Downloading phpunit/php-text-template (2.0.4)
  - Downloading phpunit/php-invoker (3.1.1)
  - Downloading phpunit/php-file-iterator (3.0.6)
  - Downloading theseer/tokenizer (1.2.1)
  - Downloading nikic/php-parser (v4.13.2)
  - Downloading sebastian/lines-of-code (1.0.3)
  - Downloading sebastian/complexity (2.0.2)
  - Downloading sebastian/code-unit-reverse-lookup (2.0.3)
  - Downloading phpunit/php-code-coverage (9.2.10)
  - Downloading doctrine/instantiator (1.4.0)
  - Downloading phpspec/prophecy (1.14.0)
  - Downloading phar-io/version (3.1.0)
  - Downloading phar-io/manifest (2.0.3)
  - Downloading myclabs/deep-copy (1.10.2)
  - Downloading phpunit/phpunit (9.5.10)
  - Installing psr/log (1.1.4): Extracting archive
  - Installing laminas/laminas-escaper (2.9.0): Extracting archive
  - Installing kint-php/kint (3.3): Extracting archive
  - Installing codeigniter4/framework (v4.1.5): Extracting archive
  - Installing symfony/deprecation-contracts (v3.0.0): Extracting archive
  - Installing psr/container (2.0.2): Extracting archive
  - Installing fakerphp/faker (v1.17.0): Extracting archive
  - Installing mikey179/vfsstream (v1.6.10): Extracting archive
  - Installing symfony/polyfill-ctype (v1.23.0): Extracting archive
  - Installing webmozart/assert (1.10.0): Extracting archive
  - Installing phpdocumentor/reflection-common (2.2.0): Extracting archive
  - Installing phpdocumentor/type-resolver (1.5.1): Extracting archive
  - Installing phpdocumentor/reflection-docblock (5.3.0): Extracting archive
  - Installing sebastian/version (3.0.2): Extracting archive
  - Installing sebastian/type (2.3.4): Extracting archive
  - Installing sebastian/resource-operations (3.0.3): Extracting archive
  - Installing sebastian/recursion-context (4.0.4): Extracting archive
  - Installing sebastian/object-reflector (2.0.4): Extracting archive
  - Installing sebastian/object-enumerator (4.0.4): Extracting archive
  - Installing sebastian/global-state (5.0.3): Extracting archive
  - Installing sebastian/exporter (4.0.4): Extracting archive
  - Installing sebastian/environment (5.1.3): Extracting archive
  - Installing sebastian/diff (4.0.4): Extracting archive
  - Installing sebastian/comparator (4.0.6): Extracting archive
  - Installing sebastian/code-unit (1.0.8): Extracting archive
  - Installing sebastian/cli-parser (1.0.1): Extracting archive
  - Installing phpunit/php-timer (5.0.3): Extracting archive
  - Installing phpunit/php-text-template (2.0.4): Extracting archive
  - Installing phpunit/php-invoker (3.1.1): Extracting archive
  - Installing phpunit/php-file-iterator (3.0.6): Extracting archive
  - Installing theseer/tokenizer (1.2.1): Extracting archive
  - Installing nikic/php-parser (v4.13.2): Extracting archive
  - Installing sebastian/lines-of-code (1.0.3): Extracting archive
  - Installing sebastian/complexity (2.0.2): Extracting archive
  - Installing sebastian/code-unit-reverse-lookup (2.0.3): Extracting archive
  - Installing phpunit/php-code-coverage (9.2.10): Extracting archive
  - Installing doctrine/instantiator (1.4.0): Extracting archive
  - Installing phpspec/prophecy (1.14.0): Extracting archive
  - Installing phar-io/version (3.1.0): Extracting archive
  - Installing phar-io/manifest (2.0.3): Extracting archive
  - Installing myclabs/deep-copy (1.10.2): Extracting archive
  - Installing phpunit/phpunit (9.5.10): Extracting archive
9 package suggestions were added by new dependencies, use `composer suggest` to see details.
Generating autoload files
28 packages you are using are looking for funding.
Use the `composer fund` command to find out more

Now, open the crud_basic folder using the Code Editor you have. Here I use VSCode. Then it will look like this:

CRUD CodeIgniter 4 With Bootstrap Basic Tutorial

Next, how to...

 

Make Database & Migration

The name of the database and the properties that we will create are as follows: 

  • Database Name: crud_ci4
  • Tabel Name: users
  • Field Name : id, name, address

 

Please open phpmyadmin, create a database manually with the database name is "crud_ci4".

Then, to create tables and fields, we use the migration feature of codeigniter.

We will create a migration file with the file name "users". Open a terminal and use the command:

php spark migrate:create users

If successful then the terminal will look like this:

neon@neon:~/Documents/Project-CI4/crud_basic$ php spark migrate:create users

CodeIgniter v4.1.5 Command Line Tool - Server Time: 2021-12-06 18:44:22 UTC-06:00

File created: APPPATH/Database/Migrations/2021-12-07-004422_Users.php

Now, go to the users migration file. This file is located in app->Database->Migrations->filename. So in the file there are only two functions, namely up() and down().

The up() function is used to create a table to the database while the down() function is used to delete the table.

in the up() function, please add the following line:

<?php

namespace App\Database\Migrations;

use CodeIgniter\Database\Migration;

class Users extends Migration
{
    public function up()
    {
        $this->forge->addField(
            [
                'id' => [
                    'type' => 'INT',
                    'constraint' => 11,
                    'unsigned' => TRUE,
                    'auto_increment' => TRUE
                ],

                'name' =>[
                    'type' => 'VARCHAR',
                    'constraint' => 255
                ],

                'address' =>[
                    'type' => 'TEXT',
                    'null' => true
                ]
            ]
        );
        $this->forge->addKey('id', TRUE);
        $this->forge->createTable('users');
    }

    public function down()
    {
        //
    }
}

After that, we will instruct codeigniter to create a table according to what has been written into the migration file. Open a terminal and use the following command:

php spark migrate

 

ERROR : MySQLi No such file or directory

If you get an error like:

[CodeIgniter\Database\Exceptions\DatabaseException]

Unable to connect to the database.
Main connection [MySQLi]: No such file or directory

That's a sign there is a problem with the database connection. Now in your project folder find the "env" file. Then copy and paste. rename the file "env (paste)" to ".env".

Open the .env file, then adjust the database settings. For example I use the following rules:

#--------------------------------------------------------------------
# ENVIRONMENT
#--------------------------------------------------------------------

CI_ENVIRONMENT = development

#--------------------------------------------------------------------
# DATABASE
#--------------------------------------------------------------------

database.default.hostname = 127.0.0.1
database.default.database = crud_ci4
database.default.username = root
database.default.password = 
database.default.DBDriver = MySQLi
database.default.DBPrefix =

After that repeat the following command in terminal:

php spark migrate

If successful, it will appear as follows:

neon@neon:~/Documents/Project-CI4/crud_basic$ php spark migrate

CodeIgniter v4.1.5 Command Line Tool - Server Time: 2021-12-07 19:49:05 UTC-06:00

Running all new migrations...
        Running: (App) 2021-12-07-004422_App\Database\Migrations\Users
Done migrations.

Now, we will see if the table was created successfully in the database. Open phpmyadmin, navigate to the crud_ci4 database, then you will see a table named "users".

The next step is to fill in the users table with any writing, whatever the words are filled with. Now is our time...

 

Show Data (Read-CRUD CodeIgniter)

To display the data we have to read the database. that's why we need...

1. Make a Model 

The function of the model is to model database usage and allow database properties to be accessed.

In CRUD CodeIgniter 4 we will create a model file using the terminal. We will create a model with the model name "UserModel". File names must start with an uppercase letter.

Go back to the terminal and use the following command:

php spark make:model UserModel

If successful, it will appear as follows:

neon@neon:~/Documents/Project-CI4/crud_basic$ php spark make:model UserModel

CodeIgniter v4.1.5 Command Line Tool - Server Time: 2021-12-07 20:10:10 UTC-06:00

File created: APPPATH/Models/UserModel.php

Open the User Model file and fill it with contents with:

<?php

namespace App\Models;

use CodeIgniter\Model;

class UserModel extends Model
{
    protected $table      = 'users';
    protected $returnType = 'object';
protected $allowedFields = ['name', 'address']; }

Now that the model has been created, it's time for us...

 

2. Make a Controller

Controller is useful for controlling anything. It contains the required functions or methods.

We will create a controller with the name "UserController".

Open terminal and use:

php spark make:controller UserController

If successful, you will see something like this:

neon@neon:~/Documents/Project-CI4/crud_basic$ php spark make:controller UserController

CodeIgniter v4.1.5 Command Line Tool - Server Time: 2021-12-07 20:35:28 UTC-06:00

File created: APPPATH/Controllers/UserController.php

Now open the controller file which is under "app->Controllers". Fill the controller file with the following data:

<?php

namespace App\Controllers;

use App\Controllers\BaseController;
use App\Models\UserModel;

class UserController extends BaseController
{
    public $userModel;

    public function __construct()
    {
        $this->userModel = new UserModel();
    }

    public function index()
    {
        $data = [
            "title" => "Show Data",
            "pengguna" => $this->userModel->findAll()
        ];

        return view('userView', $data);
    }
}

We have made the controller. Now we just have to view the data. But we have to create a route first so that when we type the link in the browser it leads to the view file. Let us...

3. Make a Route

Now open the Routes.php file which is in "app->Config". we point the route to the UserController then to the index() function. For the complete line like this:
// We get a performance increase by specifying the default
// route since we don't have to scan directories.
$routes->get('/', 'Home::index');
$routes->get('/show', 'UserController::index');
The route is useful when we access "localhost:8080/show, it will point to the UserController. 
Because in the index() function in the codeIgniter controller it commands the View file, then we will...

4. Make a View

Create a View file with filename "userView.php" inside "app->Views". Enter the following code into the view file:
<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-1BmE4kWBq78iYhFldvKuhfTAU6auU8tT94WrHftjDbrCEXSU1oBoqyl2QvZ6jIW3" crossorigin="anonymous">
    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/js/bootstrap.bundle.min.js" integrity="sha384-ka7Sk0Gln4gmtz2MlQnikT1wXgYsOg+OMhuP+IlRH9sENBO0LRn5q+8nbTov4+1p" crossorigin="anonymous"></script>
    <title><?php echo $title ?></title>
</head>

<body>
    <div class="container">
        <h1 class="mt-5 mb-5" style="text-align: center;">Show Database</h1>
        <div>
            <a href="/add" class="btn btn-primary float-end mb-1">Add Data</a>
        </div>
        <table class="table table-dark table-striped">
            <thead>
                <tr>
                    <th>Name</th>
                    <th>Address</th>
                    <th>Action</th>
                </tr>
            </thead>
            <tbody>
                <?php
                foreach ($pengguna as $key => $data) {

                ?>
                    <tr>

                        <td>
                            <?php echo $data->name ?>
                        </td>
                        <td>
                            <?php echo $data->address ?>
                        </td>
                        <td>
                            <a href="/edit/<?php echo $data->id ?>" class="btn btn-warning">Edit</a>
                            <a href="/delete/<?php echo $data->id ?>" class="btn btn-danger" onclick="return confirm('Are you sure?')">Delete</a>
                        </td>
                    </tr>
                <?php
                }
                ?>
            </tbody>
        </table>
    </div>
</body>
</html>

If run, it will appear as follows:

CRUD CodeIgniter 4 With Bootstrap Basic Tutorial

 

The data has been able to appear, it's time we create a form to add data. when the "Add Data" button is pressed, a new data input page will appear. Then next is...

 

Add Data (Create-CRUD CodeIgniter)

Inside the View file, there is an "Add Data" button, where when the button is clicked, it will lead to the "/add" link.

The first thing we have to create is, the route for the "/add" link.

Open the routes file, add the following program line:

$routes->get('/add', 'UserController::add');

Open the UserController file, then add the following function program line:

public function add()
    {
        $data = [
            "title" => "Add Data"
        ];
        return view('userAdd', $data);
    }

At this point, the controller will direct us to the add data page. For that create a file with the name "userAdd.php" in app->Views, where this file will display the form for the data.

Then copy the following program line and paste it into the userAdd file.

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

<head>
  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-1BmE4kWBq78iYhFldvKuhfTAU6auU8tT94WrHftjDbrCEXSU1oBoqyl2QvZ6jIW3" crossorigin="anonymous">
  <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/js/bootstrap.bundle.min.js" integrity="sha384-ka7Sk0Gln4gmtz2MlQnikT1wXgYsOg+OMhuP+IlRH9sENBO0LRn5q+8nbTov4+1p" crossorigin="anonymous"></script>
  <title><?php echo $title ?></title>
</head>

<body>
  <div class="container">
    <h1 class="mt-5 mb-5" style="text-align: center;">Insert Data</h1>

    <div class="row d-flex justify-content-center">

      <form method="POST" action="/save">
        <?php csrf_field(); ?>
        <div class="mb-3">
          <label for="name" class="form-label">Input Name:</label>
          <input name="name" type="text" class="form-control" id="name" aria-describedby="emailHelp">
        </div>
        <div class="mb-3">
          <label for="address" class="form-label">Input Address:</label>
          <textarea name="address" type="text" class="form-control" id="address" aria-describedby="emailHelp"></textarea>
        </div>
        <a href="/show" class="btn btn-danger">Back</a>
        <button type="submit" class="btn btn-primary">Save</button>
      </form>
    </div>
  </div>
</body>

</html>

After that, we will test the code. On the view page, click the Add Data button, the following image will appear:

CRUD CodeIgniter 4 With Bootstrap Basic Tutorial

 

After the form page appears, we must create conditions when the save button is pressed. Where when the button is pressed, the data in the form will be stored in the users table.

Open routes file, use this command:

$routes->post('/save', 'UserController::save');

 

Therefore, add the following function in UserController to save data: 

public function save()
    {
        $data = [
            'name' => $this->request->getVar('name'),
            'address' => $this->request->getVar('address')
        ];

        $this->userModel->insert($data);
        return redirect()->to('/show');
    }

Up here we have finished creating the add data feature or create data. The next is...

 

Edit Data (Update-CRUD CodeIgniter)

On the Show Data page, we can see an action button with the name "Edit". How do we when we press the edit button, we can change the data in this edit button.
First we create routes first. We will create a route 
$routes->get('/edit/(:segment)', 'UserController::edit/$1');
$routes->post('/update/(:segment)', 'UserController::update/$1');

Then we create an edit and update function in the UserController.php file, fill it with the following command code:

public function edit($id)
    {

        $data = [
            'title' => 'Update Data',
            'data' => $this->userModel->find($id)
        ];

        return view('userEdit', $data);
    }

    public function update($id)
    {
        $this->userModel->update(
            $id,
            [
                'name' => $this->request->getPost('name'),
                'address' => $this->request->getPost('address')
            ]
        );
        return redirect()->to('/show');
    }

Now, we need the page to edit, so create a file in views with the name "userEdit.php". Copy all the code below then paste it into userAdd.php:

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

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-1BmE4kWBq78iYhFldvKuhfTAU6auU8tT94WrHftjDbrCEXSU1oBoqyl2QvZ6jIW3" crossorigin="anonymous">
    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/js/bootstrap.bundle.min.js" integrity="sha384-ka7Sk0Gln4gmtz2MlQnikT1wXgYsOg+OMhuP+IlRH9sENBO0LRn5q+8nbTov4+1p" crossorigin="anonymous"></script>
    <title><?php echo $title ?></title>
</head>

<body>
    <div class="container">
        <h1 class="mt-5 mb-5" style="text-align: center;">Edit Data</h1>

        <div class="row d-flex justify-content-center">

            <form method="POST" action="/update/<?php echo ($data->id) ?>">
                <?php csrf_field(); ?>
                <div class="mb-3">
                    <label for="name" class="form-label">Input Name:</label>
                    <input name="name" type="text" class="form-control" id="name" aria-describedby="emailHelp" value="<?php echo ($data->name) ?>">
                </div>
                <div class="mb-3">
                    <label for="address" class="form-label">Input Address:</label>
                    <textarea name="address" type="text" class="form-control" id="address" aria-describedby="emailHelp"><?php echo ($data->address) ?></textarea>
                </div>
                <a href="/show" class="btn btn-danger">Back</a>
                <button type="submit" class="btn btn-primary">Save</button>
            </form>
        </div>
    </div>
</body>

</html>

Now, you can test live on the web for this crud codeigniter tutorial.

 

Delete Data (Delete -CRUD CodeIgniter)

After that, just delete the data.

The trick is to use create a route first as follows:

$routes->get('/delete/(:segment)', 'UserController::delete/$1');

then add the delete function inside the UserController:

 public function delete($id)
    {
        $this->userModel->delete($id);
        return redirect()->to('/show');
    }

CRUD codeigniter tutorial is Done.

Post a Comment for "CRUD CodeIgniter 4 With Bootstrap Basic Tutorial"