agyanadda@gmail.com

CodeIgniter Examples

30 examples 30 topics

Learn by doing. Every example below can be opened in our online editor — change the code, press Run and see the result instantly.

Open the Try it Now editor »

CodeIgniter 4 Introduction

CodeIgniter 4 Basics · 1 example
Example — Your first CodeIgniter page PHP
<?php
// app/Config/Routes.php
$routes->get('hello', 'Hello::index');

// app/Controllers/Hello.php
namespace App\Controllers;

class Hello extends BaseController
{
    public function index()
    {
        return 'Hello from CodeIgniter 4!';
    }
}

Open http://localhost:8080/hello and the browser shows: Hello from CodeIgniter 4! A route points the URL to a controller method.

CodeIgniter 4 Installation

CodeIgniter 4 Basics · 1 example
Example — Create and run a project Bash
# 1. Create the project
composer create-project codeigniter4/appstarter blog
cd blog

# 2. Create your .env from the template
cp env .env          # Windows: copy env .env

# 3. In .env, remove the # and set:
# CI_ENVIRONMENT = development
# app.baseURL = 'http://localhost:8080/'

# 4. Start the development server
php spark serve
# CodeIgniter development server started on http://localhost:8080

Open http://localhost:8080 to see the welcome page. Press Ctrl+C in the terminal to stop the server.

CodeIgniter 4 Folder Structure

CodeIgniter 4 Basics · 1 example
Example — Where each part lives PHP
<?php
// app/Config/Routes.php -> the URL
$routes->get('about', 'Pages::about');

// app/Controllers/Pages.php -> the logic
namespace App\Controllers;

class Pages extends BaseController
{
    public function about()
    {
        return view('pages/about');   // loads app/Views/pages/about.php
    }
}

// app/Views/pages/about.php -> the HTML
// <h1>About us</h1>

view('pages/about') loads app/Views/pages/about.php. View files are plain .php files.

CodeIgniter 4 Configuration and .env

CodeIgniter 4 Basics · 1 example
Example — A custom config class PHP
<?php
// app/Config/Site.php
namespace Config;

use CodeIgniter\Config\BaseConfig;

class Site extends BaseConfig
{
    public string $siteName = 'AgyanAdda';
    public string $whatsapp = '';
    public int $perPage = 12;
}

// .env (overrides the class values)
// site.whatsapp = 919876543210

// In a controller or view:
$site = config('Site');
echo $site->siteName;   // AgyanAdda
echo $site->whatsapp;   // 919876543210 (from .env)

The .env line site.whatsapp overrides the $whatsapp property of the Site class, so each server can have its own value.

CodeIgniter 4 Spark Commands

CodeIgniter 4 Basics · 1 example
Example — Generate files with spark Bash
# See every route
php spark routes

# Create a model with matching files
php spark make:model PostModel
# File created: APPPATH/Models/PostModel.php

# Controller, model, migration and seeder in one go
php spark make:scaffold Post

# Run migrations and check their status
php spark migrate
php spark migrate:status

# Clear the cache
php spark cache:clear

Each make: command creates a ready-to-edit file in the right app folder with the correct namespace.

CodeIgniter 4 Routing

CodeIgniter 4 Basics · 1 example
Example — Routes with placeholders and a group PHP
<?php
// app/Config/Routes.php
$routes->get('/', 'Home::index');
$routes->get('posts', 'Posts::index', ['as' => 'posts']);
$routes->get('posts/(:num)', 'Posts::show/$1');
$routes->get('category/(:segment)', 'Posts::category/$1');

$routes->group('admin', ['filter' => 'auth'], static function ($routes) {
    $routes->get('dashboard', 'Admin\Dashboard::index');   // /admin/dashboard
});

// app/Controllers/Posts.php
public function show(int $id)
{
    return "Post number $id";
}

/posts/5 shows "Post number 5". /posts/abc gives 404 because (:num) only matches numbers. /admin/dashboard first runs the auth filter.

CodeIgniter 4 Controllers

CodeIgniter 4 Basics · 1 example
Example — Controller passing data to a view PHP
<?php
namespace App\Controllers;

class Posts extends BaseController
{
    public function index()
    {
        $data = [
            'title' => 'Latest Posts',
            'posts' => ['Learn Routing', 'Learn Views', 'Learn Models'],
        ];

        return view('posts/index', $data);
    }
}

// app/Views/posts/index.php
// <h1><?= esc($title) ?></h1>
// <ul>
//   <?php foreach ($posts as $post): ?>
//     <li><?= esc($post) ?></li>
//   <?php endforeach ?>
// </ul>

The page shows the heading "Latest Posts" and a list of three post titles. Array keys become variables in the view.

CodeIgniter 4 Views and Layouts

CodeIgniter 4 Basics · 1 example
Example — Layout and page PHP
<!-- app/Views/layouts/main.php -->
<!DOCTYPE html>
<html>
<head><title><?= esc($title ?? 'My Site') ?></title></head>
<body>
  <?= $this->include('partials/navbar') ?>
  <main>
    <?= $this->renderSection('content') ?>
  </main>
</body>
</html>

<!-- app/Views/posts/index.php -->
<?= $this->extend('layouts/main') ?>

<?= $this->section('content') ?>
  <h1><?= esc($title) ?></h1>
  <?php foreach ($posts as $post): ?>
    <p><?= esc($post) ?></p>
  <?php endforeach ?>
<?= $this->endSection() ?>

The final page has the layout's <head>, the navbar partial, and the posts list inside <main>. The layout is written once and reused by every page.

CodeIgniter 4 Helpers

CodeIgniter 4 Basics · 1 example
Example — Custom helper and URL helpers PHP
<?php
// app/Helpers/site_helper.php
if (! function_exists('rupees')) {
    function rupees(float $amount): string
    {
        return '₹' . number_format($amount, 2);
    }
}

// app/Controllers/BaseController.php
protected $helpers = ['form', 'text', 'site'];

// In any view:
// <link rel="stylesheet" href="<?= base_url('css/style.css') ?>">
// <?= anchor('posts', 'All posts') ?>
// <p>Price: <?= rupees(1499) ?></p>
// <p><?= word_limiter($post['body'], 20) ?></p>

rupees(1499) prints ₹1,499.00. anchor() prints <a href="http://localhost:8080/posts">All posts</a>. word_limiter() shortens the text to 20 words.

CodeIgniter 4 Database and Query Builder

Database and Models · 1 example
Example — Published posts with author names PHP
<?php
$db = db_connect();

$posts = $db->table('posts')
    ->select('posts.id, posts.title, users.name AS author')
    ->join('users', 'users.id = posts.user_id')
    ->where('posts.status', 'published')
    ->like('posts.title', 'php')
    ->orderBy('posts.id', 'DESC')
    ->limit(5)
    ->get()
    ->getResultArray();

foreach ($posts as $post) {
    echo $post['title'] . ' by ' . $post['author'] . PHP_EOL;
}

// Insert and get the new id
$db->table('posts')->insert(['user_id' => 1, 'title' => 'PHP Tips', 'status' => 'draft']);
echo $db->insertID();

Prints up to 5 published posts with "php" in the title, e.g. "PHP Tips by Asha", newest first. insertID() prints the id of the row just inserted.

CodeIgniter 4 Migrations

Database and Models · 1 example
Example — Posts table migration PHP
<?php
namespace App\Database\Migrations;

use CodeIgniter\Database\Migration;

class CreatePostsTable extends Migration
{
    public function up()
    {
        $this->forge->addField([
            'id'         => ['type' => 'INT', 'constraint' => 11, 'unsigned' => true, 'auto_increment' => true],
            'user_id'    => ['type' => 'INT', 'constraint' => 11, 'unsigned' => true],
            'title'      => ['type' => 'VARCHAR', 'constraint' => 255],
            'slug'       => ['type' => 'VARCHAR', 'constraint' => 255],
            'body'       => ['type' => 'TEXT'],
            'status'     => ['type' => 'VARCHAR', 'constraint' => 20, 'default' => 'draft'],
            'created_at' => ['type' => 'DATETIME', 'null' => true],
            'updated_at' => ['type' => 'DATETIME', 'null' => true],
        ]);
        $this->forge->addKey('id', true);
        $this->forge->addUniqueKey('slug');
        $this->forge->addForeignKey('user_id', 'users', 'id', 'CASCADE', 'CASCADE');
        $this->forge->createTable('posts');
    }

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

php spark migrate creates the posts table with a primary key, a unique slug and a foreign key to users. migrate:rollback drops it again.

CodeIgniter 4 Seeders

Database and Models · 1 example
Example — Categories and an admin user PHP
<?php
namespace App\Database\Seeds;

use CodeIgniter\Database\Seeder;

class DatabaseSeeder extends Seeder
{
    public function run()
    {
        $this->db->table('users')->insert([
            'name'     => 'Admin',
            'email'    => 'admin@example.com',
            'password' => password_hash('admin123', PASSWORD_DEFAULT),
        ]);

        $this->db->table('categories')->insertBatch([
            ['name' => 'PHP',        'slug' => 'php'],
            ['name' => 'JavaScript', 'slug' => 'javascript'],
            ['name' => 'MySQL',      'slug' => 'mysql'],
        ]);

        $this->call('PostSeeder');   // run another seeder
    }
}

// Terminal:
// php spark db:seed DatabaseSeeder

Creates one admin user with a hashed password, three categories in a single query, then runs PostSeeder.

CodeIgniter 4 Models

Database and Models · 1 example
Example — PostModel with a custom method PHP
<?php
namespace App\Models;

use CodeIgniter\Model;

class PostModel extends Model
{
    protected $table          = 'posts';
    protected $primaryKey     = 'id';
    protected $allowedFields  = ['user_id', 'title', 'slug', 'body', 'status'];
    protected $returnType     = 'array';
    protected $useTimestamps  = true;

    public function getPublished(int $limit = 10): array
    {
        return $this->where('status', 'published')
                    ->orderBy('id', 'DESC')
                    ->findAll($limit);
    }
}

// In a controller
$posts = model(PostModel::class);
$id    = $posts->insert(['user_id' => 1, 'title' => 'Hello CI4', 'slug' => 'hello-ci4', 'body' => '...', 'status' => 'published']);
$post  = $posts->find($id);
echo $post['title'];   // Hello CI4

insert() saves the row (filling created_at and updated_at) and returns its id; find() reads it back as an array.

CodeIgniter 4 Entities

Database and Models · 1 example
Example — Post entity with a slug setter PHP
<?php
namespace App\Entities;

use CodeIgniter\Entity\Entity;

class Post extends Entity
{
    protected $casts = ['is_featured' => 'boolean'];

    public function setTitle(string $title)
    {
        $this->attributes['title'] = $title;
        $this->attributes['slug']  = url_title($title, '-', true);

        return $this;
    }

    public function excerpt(int $words = 20): string
    {
        helper('text');
        return word_limiter(strip_tags($this->attributes['body'] ?? ''), $words);
    }
}

// Usage (PostModel has $returnType = \App\Entities\Post::class)
$post = new \App\Entities\Post();
$post->title = 'My First Entity Post';
$post->body  = 'Entities make data easy to work with.';
model('PostModel')->save($post);

echo $post->slug;   // my-first-entity-post

Assigning the title also creates the slug "my-first-entity-post". excerpt() can be called in views as $post->excerpt().

CodeIgniter 4 CRUD Application

Database and Models · 1 example
Example — Posts controller: store, update, delete PHP
<?php
namespace App\Controllers;

use App\Models\PostModel;
use CodeIgniter\Exceptions\PageNotFoundException;

class Posts extends BaseController
{
    private array $rules = ['title' => 'required|max_length[255]', 'body' => 'required'];

    public function create()
    {
        if (! $this->validate($this->rules)) {
            return redirect()->back()->withInput();
        }
        model(PostModel::class)->insert($this->request->getPost(['title', 'body']));

        return redirect()->to('posts')->with('success', 'Post created');
    }

    public function update(int $id)
    {
        $model = model(PostModel::class);
        $model->find($id) ?? throw PageNotFoundException::forPageNotFound();

        if (! $this->validate($this->rules)) {
            return redirect()->back()->withInput();
        }
        $model->update($id, $this->request->getPost(['title', 'body']));

        return redirect()->to('posts')->with('success', 'Post updated');
    }

    public function delete(int $id)
    {
        model(PostModel::class)->delete($id);

        return redirect()->to('posts')->with('success', 'Post deleted');
    }
}

// Routes.php
// $routes->get('posts', 'Posts::index');
// $routes->post('posts', 'Posts::create');
// $routes->post('posts/(:num)/update', 'Posts::update/$1');
// $routes->post('posts/(:num)/delete', 'Posts::delete/$1');

Invalid input sends the user back to the form with the errors and old values. A valid save redirects to /posts with a one-time success message. Updating an id that does not exist shows a 404 page.

CodeIgniter 4 Pagination

Database and Models · 1 example
Example — Paginated search PHP
<?php
// app/Controllers/Posts.php
public function index()
{
    $model = model(PostModel::class);
    $q     = trim((string) $this->request->getGet('q'));

    if ($q !== '') {
        $model->like('title', $q);
    }

    return view('posts/index', [
        'posts' => $model->orderBy('id', 'DESC')->paginate(10),
        'pager' => $model->pager,
        'q'     => $q,
    ]);
}

// app/Views/posts/index.php
// <?php foreach ($posts as $post): ?>
//   <h3><?= esc($post['title']) ?></h3>
// <?php endforeach ?>
// <?= $pager->only(['q'])->links() ?>
// <p>Page <?= $pager->getCurrentPage() ?> of <?= $pager->getPageCount() ?></p>

/posts?q=php&page=2 shows the second page of posts with "php" in the title. Page links keep q=php, and the text shows e.g. "Page 2 of 4".

CodeIgniter 4 Request and Response

Forms, Sessions and Security · 1 example
Example — Contact form handler with JSON for AJAX PHP
<?php
public function send()
{
    $data = $this->request->getPost(['name', 'email', 'message']);

    if (! $this->validateData($data, [
        'name'    => 'required|max_length[100]',
        'email'   => 'required|valid_email',
        'message' => 'required|min_length[10]',
    ])) {
        if ($this->request->isAJAX()) {
            return $this->response->setStatusCode(422)->setJSON(['errors' => $this->validator->getErrors()]);
        }
        return redirect()->back()->withInput();
    }

    model('ContactModel')->insert($data);

    return $this->request->isAJAX()
        ? $this->response->setJSON(['ok' => true])
        : redirect()->to('contact')->with('success', 'Thank you! We will reply soon.');
}

A normal form post redirects with a success message. An AJAX post gets {"ok":true}, or status 422 with {"errors":{...}} when validation fails.

CodeIgniter 4 Form Validation

Forms, Sessions and Security · 1 example
Example — Registration validation PHP
<?php
public function register()
{
    $rules = [
        'name'             => 'required|min_length[3]|max_length[100]',
        'email'            => 'required|valid_email|is_unique[users.email]',
        'mobile'           => 'required|regex_match[/^[6-9][0-9]{9}$/]',
        'password'         => 'required|min_length[8]',
        'password_confirm' => 'required|matches[password]',
    ];
    $messages = [
        'email'  => ['is_unique' => 'This email is already registered.'],
        'mobile' => ['regex_match' => 'Enter a valid 10-digit mobile number.'],
    ];

    if (! $this->validate($rules, $messages)) {
        return redirect()->back()->withInput();
    }

    $data = $this->validator->getValidated();
    unset($data['password_confirm']);
    $data['password'] = password_hash($data['password'], PASSWORD_DEFAULT);
    model('UserModel')->insert($data);

    return redirect()->to('login')->with('success', 'Account created. Please log in.');
}

// View:
// <input name="email" value="<?= old('email') ?>">
// <span class="text-danger"><?= validation_show_error('email') ?></span>

If the email is taken, the form comes back with "This email is already registered." under the email field and the other fields still filled in.

CodeIgniter 4 Sessions and Flash Data

Forms, Sessions and Security · 1 example
Example — Simple cart in the session PHP
<?php
public function addToCart(int $productId)
{
    $cart = session('cart') ?? [];
    $cart[$productId] = ($cart[$productId] ?? 0) + 1;

    session()->set('cart', $cart);

    return redirect()->back()->with('success', 'Added to cart');
}

public function cartCount(): int
{
    return array_sum(session('cart') ?? []);
}

// View (layout)
// <?php if (session()->getFlashdata('success')): ?>
//   <div class="alert alert-success"><?= esc(session()->getFlashdata('success')) ?></div>
// <?php endif ?>

Each click adds one of the product to the cart stored in the session. The "Added to cart" message shows once and disappears on the next page load.

CodeIgniter 4 Filters

Forms, Sessions and Security · 1 example
Example — Login and role filters PHP
<?php
namespace App\Filters;

use CodeIgniter\Filters\FilterInterface;
use CodeIgniter\HTTP\RequestInterface;
use CodeIgniter\HTTP\ResponseInterface;

class AuthFilter implements FilterInterface
{
    public function before(RequestInterface $request, $arguments = null)
    {
        if (! session('user_id')) {
            return redirect()->to('login')->with('error', 'Please log in first.');
        }

        // ['filter' => 'auth:admin'] -> $arguments = ['admin']
        if ($arguments && ! in_array(session('role'), $arguments, true)) {
            return redirect()->to('/')->with('error', 'You do not have access.');
        }
    }

    public function after(RequestInterface $request, ResponseInterface $response, $arguments = null)
    {
    }
}

// app/Config/Filters.php  ->  public array $aliases = [ ..., 'auth' => \App\Filters\AuthFilter::class ];

// app/Config/Routes.php
// $routes->get('dashboard', 'Dashboard::index', ['filter' => 'auth']);
// $routes->group('admin', ['filter' => 'auth:admin'], static function ($routes) { ... });

Guests who open /dashboard are sent to /login. Logged-in users without the admin role are sent to the home page when they open any /admin URL.

CodeIgniter 4 Login and Registration

Forms, Sessions and Security · 1 example
Example — Login and logout PHP
<?php
namespace App\Controllers;

class Auth extends BaseController
{
    public function login()
    {
        if (! $this->validate(['email' => 'required|valid_email', 'password' => 'required'])) {
            return redirect()->back()->withInput();
        }

        $user = model('UserModel')->where('email', $this->request->getPost('email'))->first();

        if (! $user || ! password_verify($this->request->getPost('password'), $user['password'])) {
            return redirect()->back()->withInput()->with('error', 'Invalid email or password.');
        }

        session()->regenerate();
        session()->set(['user_id' => $user['id'], 'name' => $user['name'], 'role' => $user['role']]);

        return redirect()->to('dashboard');
    }

    public function logout()
    {
        session()->destroy();

        return redirect()->to('login')->with('success', 'You have logged out.');
    }
}

Correct details log the user in and open /dashboard. Wrong details return to the form with "Invalid email or password." Logout ends the session.

CodeIgniter 4 File Upload

Forms, Sessions and Security · 1 example
Example — Profile photo upload PHP
<?php
public function uploadPhoto()
{
    $valid = $this->validate([
        'photo' => 'uploaded[photo]|is_image[photo]|mime_in[photo,image/jpeg,image/png,image/webp]|max_size[photo,2048]',
    ]);
    if (! $valid) {
        return redirect()->back()->with('error', $this->validator->getError('photo'));
    }

    $file = $this->request->getFile('photo');

    if ($file->isValid() && ! $file->hasMoved()) {
        $name = $file->getRandomName();
        $file->move(FCPATH . 'uploads/photos', $name);

        model('UserModel')->update(session('user_id'), ['photo' => $name]);
    }

    return redirect()->back()->with('success', 'Photo updated');
}

// View:
// <?= form_open_multipart('profile/photo') ?>
//   <input type="file" name="photo" accept="image/*">
//   <button>Upload</button>
// <?= form_close() ?>
// <img src="<?= base_url('uploads/photos/' . esc($user['photo'])) ?>" width="120">

A valid image up to 2 MB is saved as public/uploads/photos/<random-name>.jpg and its name stored for the user. Anything else returns with an error such as "photo is too large".

CodeIgniter 4 Security: CSRF, XSS and SQL Injection

Forms, Sessions and Security · 1 example
Example — Enable CSRF and use it in forms and AJAX PHP
<?php
// app/Config/Filters.php
public array $globals = [
    'before' => [
        'csrf',          // <- uncomment / add this
        // 'honeypot',
    ],
    'after' => [
        // 'secureheaders',
    ],
];

// In a form view:
// <form method="post" action="<?= site_url('comments') ?>">
//     <?= csrf_field() ?>
//     <textarea name="comment"></textarea>
//     <button>Post</button>
// </form>

// Printing user content safely:
// <p><?= esc($comment['text']) ?></p>

// AJAX (JavaScript) - send the token with the request:
// fetch('/comments', {
//   method: 'POST',
//   headers: { 'X-Requested-With': 'XMLHttpRequest' },
//   body: new URLSearchParams({ comment: 'Hi', '<?= csrf_token() ?>': '<?= csrf_hash() ?>' })
// });

With the csrf filter on, a POST without a valid token is rejected with an error. A comment like <script>alert(1)</script> is shown as text, not run, because of esc().

CodeIgniter 4 REST API

APIs and Advanced Topics · 1 example
Example — Products API PHP
<?php
namespace App\Controllers\Api;

use CodeIgniter\RESTful\ResourceController;

class Products extends ResourceController
{
    protected $modelName = 'App\Models\ProductModel';
    protected $format    = 'json';

    public function index()
    {
        return $this->respond($this->model->orderBy('id', 'DESC')->findAll(20));
    }

    public function show($id = null)
    {
        $product = $this->model->find($id);

        return $product ? $this->respond($product) : $this->failNotFound('Product not found');
    }

    public function create()
    {
        $data = $this->request->getJSON(true) ?? [];

        if (! $this->validateData($data, ['name' => 'required|max_length[100]', 'price' => 'required|decimal'])) {
            return $this->failValidationErrors($this->validator->getErrors());
        }
        $id = $this->model->insert($data);

        return $this->respondCreated($this->model->find($id));
    }
}

// app/Config/Routes.php
// $routes->group('api', ['namespace' => 'App\Controllers\Api'], static function ($routes) {
//     $routes->resource('products', ['except' => 'new,edit']);
// });

GET /api/products returns a JSON list. GET /api/products/99 returns 404 {"messages":{"error":"Product not found"}} if it does not exist. POST /api/products with JSON {"name":"Pen","price":"20.00"} returns 201 and the new product.

CodeIgniter 4 Sending Email

APIs and Advanced Topics · 1 example
Example — Welcome email PHP
<?php
// .env
// email.fromEmail  = no-reply@agyanadda.com
// email.fromName   = AgyanAdda
// email.protocol   = smtp
// email.SMTPHost   = smtp.hostinger.com
// email.SMTPUser   = no-reply@agyanadda.com
// email.SMTPPass   = your-password
// email.SMTPPort   = 465
// email.SMTPCrypto = ssl
// email.mailType   = html

public function sendWelcome(array $user): bool
{
    $email = service('email');

    $email->setTo($user['email']);
    $email->setSubject('Welcome to AgyanAdda!');
    $email->setMessage(view('emails/welcome', ['name' => $user['name']]));

    if (! $email->send()) {
        log_message('error', $email->printDebugger(['headers']));
        return false;
    }

    return true;
}

// app/Views/emails/welcome.php
// <h2>Hi <?= esc($name) ?>,</h2>
// <p>Thanks for joining. Start learning today!</p>

The user receives an HTML email "Hi Asha, Thanks for joining...". If sending fails, the SMTP error is written to writable/logs instead of breaking the page.

CodeIgniter 4 Caching

APIs and Advanced Topics · 1 example
Example — Cache homepage data PHP
<?php
public function index()
{
    $posts = cache()->remember('home_latest_posts', 1800, static function () {
        return model('PostModel')
            ->where('status', 'published')
            ->orderBy('id', 'DESC')
            ->findAll(10);
    });

    $categories = cache()->remember('all_categories', 86400, static fn () => model('CategoryModel')->findAll());

    return view('home', compact('posts', 'categories'));
}

// After saving a post (in the admin controller):
cache()->delete('home_latest_posts');

The first visitor runs the queries; for the next 30 minutes (posts) and 24 hours (categories) the data comes from writable/cache. Saving a post clears the posts cache, so changes show at once.

CodeIgniter 4 Error Handling and Logging

APIs and Advanced Topics · 1 example
Example — Logging a failed API call PHP
<?php
use CodeIgniter\Exceptions\PageNotFoundException;

public function show(string $slug)
{
    $post = model('PostModel')->where('slug', $slug)->first();

    if (! $post) {
        throw PageNotFoundException::forPageNotFound("Post '$slug' not found");
    }

    try {
        $client   = service('curlrequest');
        $response = $client->get('https://api.example.com/views/' . $post['id'], ['timeout' => 3]);
        $views    = json_decode($response->getBody(), true)['views'] ?? 0;
    } catch (\Throwable $e) {
        log_message('error', 'View counter failed for post {id}: {msg}', ['id' => $post['id'], 'msg' => $e->getMessage()]);
        $views = 0;
    }

    return view('posts/show', compact('post', 'views'));
}

An unknown slug shows your 404 page. If the external API is down, the page still loads with 0 views, and a line like "ERROR - ... View counter failed for post 12: ..." is written to writable/logs.

CodeIgniter 4 Testing

APIs and Advanced Topics · 1 example
Example — Feature tests for posts PHP
<?php
namespace Tests\Feature;

use CodeIgniter\Test\CIUnitTestCase;
use CodeIgniter\Test\DatabaseTestTrait;
use CodeIgniter\Test\FeatureTestTrait;

class PostsTest extends CIUnitTestCase
{
    use DatabaseTestTrait;
    use FeatureTestTrait;

    protected $refresh = true;   // fresh migrations for each test class

    public function testHomePageLoads(): void
    {
        $this->get('/')->assertOK();
    }

    public function testGuestIsRedirectedFromDashboard(): void
    {
        $this->get('dashboard')->assertRedirectTo('/login');
    }

    public function testLoggedInUserCanCreatePost(): void
    {
        $this->withSession(['user_id' => 1])
            ->post('posts', ['title' => 'Test post', 'body' => 'Hello'])
            ->assertRedirect();

        $this->seeInDatabase('posts', ['title' => 'Test post']);
    }
}

vendor/bin/phpunit runs the three tests and reports OK (3 tests). If someone breaks the auth filter later, testGuestIsRedirectedFromDashboard fails.

CodeIgniter 4 Deployment

APIs and Advanced Topics · 1 example
Example — VPS deployment steps Bash
cd /var/www/myapp

# 1. Get the latest code
git pull origin main

# 2. Install packages without dev tools
composer install --no-dev --optimize-autoloader

# 3. Run database migrations
php spark migrate

# 4. Clear the cache
php spark cache:clear

# 5. Permissions for the writable folder (first deploy)
sudo chown -R www-data:www-data writable
sudo chmod -R 775 writable

# Apache virtual host (document root must be public):
# DocumentRoot /var/www/myapp/public
# <Directory /var/www/myapp/public>
#     AllowOverride All
# </Directory>

After these steps the site runs the new code. AllowOverride All lets public/.htaccess remove index.php from URLs.

CodeIgniter 4 Best Practices

APIs and Advanced Topics · 1 example
Example — Before and after: avoid queries in a loop PHP
<?php
// ❌ Before: one extra query for every post (N+1)
$posts = model('PostModel')->findAll();
foreach ($posts as &$post) {
    $post['author'] = model('UserModel')->find($post['user_id'])['name'];
}

// ✅ After: one query with a join, only needed columns, paginated
$model = model('PostModel');
$posts = $model->select('posts.id, posts.title, posts.slug, users.name AS author')
               ->join('users', 'users.id = posts.user_id')
               ->where('posts.status', 'published')
               ->orderBy('posts.id', 'DESC')
               ->paginate(12);

return view('posts/index', ['posts' => $posts, 'pager' => $model->pager]);

The first version runs 1 + (number of posts) queries. The second runs one query (plus a count for pagination) and loads only 12 rows.