While developing applications on the CodeIgniter 4 framework, you may require rich text area fields. In such cases, CKEditor 5 is a great option. This tutorial guides you through how to integrate CKEditor 5 in Codeigniter 4, including CKFinder for image upload to the server.

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'll show how to integrate CKEditor 5 in Codeigniter 4, along with CKFinder for image uploads. This will include steps to upload and insert an image in CKEditor using Codeigniter 4.

3 Create / Install a Codeigniter 4 Project

3.1 Install Codeigniter 4 Project

Ensure your system has Composer installed. Use the command below to create a 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

To store image data, modify the .env file with your 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

Include CKEditor 5’s CDN link in your app/Views/post.php file:

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

5 Create Migration and Model

Create a migration for the posts table and a model to store data:

php spark make:model PostModel

Edit app/Models/PostModel.php to configure the model for post management:

<?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    = [];
}

Create a migration file for the posts table:

php spark make:migration AddPost

Edit the migration file to define the table structure:

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

Run the migration:

php spark migrate

6 Create New Controller (CkeditorController)

Create CkeditorController to handle file uploads:

php spark make:controller CkeditorController

In 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

In app/Config/Routes.php, define routes for the controller:


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 post.php to display a form with CKEditor integration:


  <!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

Here’s the folder structure for the project:

11 Run Web Server to Test the App

Start the server:

php spark serve

Visit http://localhost:8080/ckeditor to see the integration in action. This setup demonstrates how to integrate CKEditor 5 in Codeigniter 4 and allows you to upload and insert images in CKEditor using Codeigniter 4.

11 Conclusion

By following this guide, you can easily integrate CKEditor 5 in Codeigniter 4 with image upload functionality using CKFinder.

Reference URL

Tags