While we are developing Applications on Codeigniter 4 framework sometimes we need rich text area fields. In these kind of cases, CKEditor is one of the best option for us. This tutorial will guide you through the process of integrating CKEditor with CKFinder for image upload to the server in Codeigniter App.

Codeigniter 4 CKEditor 5 -  Implementing CKEditor 
(WYSIWYG) with CKFinder for image upload to the server

Table Of Content

1 Prerequisites

1.) PHP version of 8.2
2.) MySql
3.) CKEditor 5

2 Introduction

In this article, I am going to show you how to Integrate CKEditor 5 to your Codeigniter 4 Application.

3 Create / Install a Codeigniter 4 Project

3.1 Install Codeigniter 4 Project

First, make sure your computer has a composer.
Use the following command to install new Codeigniter Project.

composer create-project codeigniter4/appstarter ci-4-ckeditor-app

Then, navigate to your project directory:

cd ci-4-ckeditor-app

3.2 Configure MySql Database

Upon Successful Transaction, the payment trasactions data will be stored in the database. This process involves accessing the .env file to input and define the database credentials.

database.default.hostname = localhost
database.default.database = codeigniter_4
database.default.username = root
database.default.password = 
database.default.DBDriver = MySQLi
database.default.DBPrefix =
database.default.port = 3306

4 Install CKEditor 5

In your app/Views/post.php file, include CKEditor 5's CDN link within the head section:

    <script src="https://cdn.ckeditor.com/ckeditor5/41.4.2/classic/ckeditor.js"></script>

5 Create Migration and Model

Now, you need to create migration for new table posts to store the data. Also, create a model Post for the same. Run this below command.

php spark make:model PostModel

open the created model at app/Models/PostModel.php. Inside the file you can see configuration options, you can read the documentation to further learn about its configuration options. We will now update the configs: app/Models/PostModel.php

<?php
namespace App\Models;

use CodeIgniter\Model;

class PostModel extends Model
{
    protected $table            = 'payments';
    protected $primaryKey       = 'id';
    protected $useAutoIncrement = true;
    protected $returnType       = 'array';
    protected $useSoftDeletes   = false;
    protected $protectFields    = true;
    protected $allowedFields    = ['title','description'];

    protected bool $allowEmptyInserts = false;
    protected bool $updateOnlyChanged = true;

    protected array $casts = [];
    protected array $castHandlers = [];

    // Dates
    protected $useTimestamps = false;
    protected $dateFormat    = 'datetime';
    protected $createdField  = 'created_at';
    protected $updatedField  = 'updated_at';
    protected $deletedField  = 'deleted_at';

    // Validation
    protected $validationRules      = [];
    protected $validationMessages   = [];
    protected $skipValidation       = false;
    protected $cleanValidationRules = true;

    // Callbacks
    protected $allowCallbacks = true;
    protected $beforeInsert   = [];
    protected $afterInsert    = [];
    protected $beforeUpdate   = [];
    protected $afterUpdate    = [];
    protected $beforeFind     = [];
    protected $afterFind      = [];
    protected $beforeDelete   = [];
    protected $afterDelete    = [];
}

After creating the model, we will then create a migration file. Run this below command.

php spark make:migration AddPost

Open the created migration file on app/Database/Migrations/ and paste these codes:

<?php
namespace App\Database\Migrations;

use CodeIgniter\Database\Migration;

class AddPost extends Migration
{
    public function up()
    {
        $this->forge->addField([
            'id' => [
                'type' => 'BIGINT',
                'constraint' => 255,
                'unsigned' => true,
                'auto_increment' => true
            ],
            'title' => [
                'type' => 'VARCHAR',
                'constraint' => '255',
            ],
            'description' => [
                'type' => 'longtext'
            ],
            'created_at' => [
                'type' => 'TIMESTAMP',
                'null' => true
            ],
            'updated_at' => [
                'type' => 'TIMESTAMP',
                'null' => true
            ],
        ]);
        $this->forge->addPrimaryKey('id');
        $this->forge->createTable('posts');
    }

    public function down()
    {
        $this->forge->dropTable('payments');
    }
}

Use the following command to run the migration to update your database.

php spark migrate

6 Create New Controller - CkeditorController

Now create a controller "CkeditorController" and add index() and store() methods, also Create "media" folder under Public Directory to store Images
Use the following artisan command to Create Controller.

php spark make:controller CkeditorController

app/Controllers/CkeditorController.php

<?php
namespace App\Controllers;

use App\Controllers\BaseController;
use CodeIgniter\HTTP\ResponseInterface;
use App\Models\PostModel;
use CodeIgniter\Files\File;


class CkeditorController extends BaseController
{
    private $postModel;

    public function __construct()
    {
        $this->postModel = new PostModel();
    }

    public function index()
    {
        return view('post');
    }
    public function upload()
    {
        $img = $this->request->getFile('upload');
        $image = $img->getRandomName();
        if ($img->move("media", $image)) 
        {
        $url=base_url()."/media/".$image;
         return json_encode(['fileName' => $image, 'uploaded'=> 1, 'url' => $url]);
        }
    }
    public function store()
    {
        $data = [
            "title" => $this->request->getVar("title"),
            "description" => $this->request->getVar("description"),
        ];
        $this->postModel->insert($data);
        
        return redirect()->back()->with('message',"Post Created Successful");

    }
}
?>

7 Define a Route

Define routes for the CkeditorController in the Routes.php file
app/Config/Routes.php


use CodeIgniter\Router\RouteCollection;
$routes->get('/', 'Home::index');
$routes->get('ckeditor', 'CkeditorController::index');  
$routes->post('upload', 'CkeditorController::upload');
$routes->post('store', 'CkeditorController::store');

8 Create Post View File

Create View "post.php" File to Show Form app/Views/post.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">
   <title>Codeigniter 4  Ckeditor Image Upload Example with CKFinder</title>
   <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0/css/all.min.css">
   <link rel="stylesheet" href="https://mdbcdn.b-cdn.net/wp-content/themes/mdbootstrap4/docs-app/css/dist/mdb5/standard/core.min.css">
   <link rel='stylesheet' id='roboto-subset.css-css'  href='https://mdbcdn.b-cdn.net/wp-content/themes/mdbootstrap4/docs-app/css/mdb5/fonts/roboto-subset.css?ver=3.9.0-update.5' type='text/css' media='all' />
   <script src="https://cdn.ckeditor.com/ckeditor5/41.4.2/classic/ckeditor.js"></script>
   <style>
    .ck-editor__editable_inline {
        min-height: 300px;
    }
    </style>
</head>
 <body>
  
 <div class="container-fluid">
 <?php if (session()->getFlashdata('message')) : ?>
                            <div 
                                style="color: green;
                                    border: 2px green solid;
                                    text-align: center;
                                    padding: 5px;margin-bottom: 10px;">
                                Post Created Successfull!
                            </div>
                        <?php endif ?>
  <div class="row">
  <div class="col-md-3"></div>
    <div class="col-md-6 mb-4">
      <div class="card mb-4">
        <div class="card-header py-3">
          <h5 class="mb-0">CodeIgniter 4 Ckeditor Image Upload Example with CKFinder</h5>
        </div>
        <div class="card-body">
        <form class="form-horizontal" method="POST" id="post-form" role="form" action="<?php echo base_url();?>store" >
         
            <div class="row mb-4">
              <div class="col">
                <div data-mdb-input-init class="form-outline">
                  <input type="text" id="name" class="form-control" name="title" />
                  <label class="form-label" for="name">Title</label>
                </div>
              </div>
              
            </div>

            
            <div class="row">
              <div class="row mb-4">
              <div class="col-12">
                <div data-mdb-input-init class="form-outline">
                <label class="form-label" for="name">Description</label> 
                <textarea name="description" id="editor" rows="5"></textarea>
                 
                </div>
              </div>
              
            </div>
              
            <hr class="my-4" />

           
            <button class="btn btn-primary btn-lg btn-block" type="submit">
              Save
            </button>
          </form>
        </div>
      </div>
    </div>
    <div class="col-md-3"></div>
    
  </div>
  </div>
  <script type="text/javascript" src="https://mdbcdn.b-cdn.net/wp-content/themes/mdbootstrap4/docs-app/js/dist/mdb5/standard/core.min.js"></script>
    

    
    <script type="text/javascript" src="https://mdbcdn.b-cdn.net/wp-content/themes/mdbootstrap4/docs-app/js/dist/search/search.min.js"></script>
<script>
    ClassicEditor
        .create( document.querySelector( '#editor' ),{
            ckfinder: {
                uploadUrl: 'upload',
            }
        })
        .catch( error => {
              
        } );
</script>

</body>
</html>

9 Folder Structure

11 Run Web Server to Test the App

Use the following command to Test the App.

php spark serve

Visit the URL http://localhost:8080/index.php/ckeditor

11 Conclusion

That’s all we need to do.
Now you can easily use the CKEditor 5 in Codeigniter 4 application. You can try it out.

Tags