This website uses cookies

Our website, platform and/or any sub domains use cookies to understand how you use our services, and to improve both your experience and our marketing relevance.

[WEBINAR: April 29] Learn How To Take Control of Cloudflare Enterprise on Cloudways. Register Now→

How to Pass Data From Controller to View in CodeIgniter 4 [Detailed Tutorial]

Updated on July 29, 2025

12 Min Read

Key Takeaways

  • Controllers pass data to views in CodeIgniter using associative arrays and the view() helper.
  • You can pass simple values or structured arrays like product lists grouped by category.
  • Dynamic data (e.g., from a database) is fetched via models and passed through the controller.
  • Keeping logic in controllers and presentation in views ensures clean, scalable code.
  • This approach powers real-world features like user greetings, product listings, and filtered pages.

When you’re building any kind of web app, one of the first things you’ll need to figure out is how to pass data from your controller to your view. This is core to how MVC frameworks work.

In this walkthrough, we’ll start with a simple controller that passes a title, a message, and a list to the view — just enough to confirm everything’s wired up correctly.

Then we’ll take things further by simulating a real-world example: a product listing page with categories and price filters. You’ll see how to pass more complex, structured data, how to organize it, and how to make your view flexible enough to scale with your app.

Let’s get started.

How Does the Model-View-Controller (MVC) Work in Web Apps?

In web development, especially with frameworks like CodeIgniter, we follow a pattern called Model-View-Controller (MVC). Think of it like a restaurant:

  • The Controller is the waiter. You (the user) tell the waiter what you want (e.g., “Show me the menu”). The waiter goes to the kitchen.
  • The Model is the kitchen and pantry. This is where all the food (data) is stored and prepared. The waiter gets the food from here.
  • The View is your table and plate. This is where the food is finally presented to you in a nice way.

Now, imagine the waiter (Controller) gets the food (data) from the kitchen (Model). They can’t just throw the food at you. They need to put it nicely on a plate (pass data to the View) so you can eat it.

That’s exactly why we pass data from the Controller to the View. The View’s job is to show stuff, but it needs the Controller to give it the actual information to display.

Why Is Passing Data Important?

Without the Controller passing data, your web pages would be stuck showing the exact same things every time. They couldn’t show:

  • Your blog posts (because the Controller needs to get them from the database and send them to the page).
  • Your shopping cart items (same reason).
  • Error messages if you fill out a form wrong.
  • Your name if you’re logged in.

Basically, if it changes or comes from somewhere else (like a database), the Controller has to grab it and pass it to the View so the View can display it.

Simple Example: Displaying a User’s Name

Let’s say you have a website, and when a user logs in, you want to show “Welcome, John Doe!”

  1. You (the user) log in.
  2. The Controller handles your login request. It checks your username and password.
  3. The Controller then asks the Model (our database kitchen) for your full name, “John Doe.”
  4. Now the Controller has “John Doe.” It needs to show this on the webpage. So, it passes “John Doe” to the View.
  5. The View receives “John Doe” and puts it into the welcome message on the page, like “Welcome, John Doe!”

This simple act of the Controller giving “John Doe” to the View is what makes your web pages dynamic and personalized. To validate user input before passing it, see CodeIgniter form validation with the Controller.

Optimized PHP Hosting for CodeIgniter

Give your CodeIgniter project the speed it deserves. Cloudways provides optimized PHP hosting designed for peak performance, ensuring your application runs flawlessly.

How to Pass Data From Controller to View in CodeIgniter 4 (Step by Step)

This tutorial will walk you through the process of passing various types of data from your CodeIgniter 4 controller to your views. We’ll start with static data (strings, arrays) and then move on to fetching dynamic data from a database.

Tutorial Objective

We’ll learn how to:

  • Create a controller in CodeIgniter.
  • Pass different types of data (string, array, associative array) from that controller.
  • Receive and render that data in a view.

Prerequisites

Before diving in, make sure you have the following set up:

  • PHP installed (PHP 8.0+ is fine, though CodeIgniter 4.6+ needs PHP 8.1+)
  • Composer installed (Download Composer)
  • XAMPP installed and running (Apache service should be ON)
  • CodeIgniter project created (we’ll do this below)

Step 1: Create a CodeIgniter Project

We’ll use Composer to create a new CodeIgniter 4 project.

In your Command Prompt, run:

composer create-project codeigniter4/appstarter codeigniter-tutorial

This creates a fresh CI4 project inside the codeigniter-tutorial folder. For me, inside, “C:\Users\abdulrehman\codeigniter-tutorial” I can see the full CodeIgniter 4 appstarter structure, including:

  • /app – Your application code (controllers, views, models, etc.)
  • /public – The folder you’ll serve in the browser (this is your web root)
  • /writable – Runtime files like logs, cache, uploads
  • .env – Environment config (rename it if you want to use it)

Step 2: Serve the Project

Navigate to your project folder:

cd C:\Users\abdulrehman\codeigniter-tutorial

Then start the local development server:

php spark serve

Visit your browser at:

http://localhost:8080

You should see:

Welcome to CodeIgniter 4.4.8
The small framework with powerful features

That means CodeIgniter is working.

Step 3: Create a New Controller

Let’s create a controller called Message.php. To do this:

  • Inside app/Controllers, create a new file: Message.php

  • Add this code:
<?php

namespace App\Controllers;

class Message extends BaseController
{
    public function index()
    {
        $data = [
            'title' => 'Welcome to CodeIgniter!',
            'message' => 'This is a message passed from the controller to the view.',
            'items' => ['Apple', 'Banana', 'Cherry']
        ];

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

What’s Happening Here?

  • index() is the default method that runs when you visit localhost:8080/message.
  • $data is an associative array that contains:
    • A string (title)
    • A string (message)
    • An indexed array (items)
  • return view(‘message_view’, $data); tells CodeIgniter:
    • Load the view file message_view.php (we’ll create that next)
    • And pass the $data array into that view

Step 4: Create the View

Let’s create the file message_view.php inside the app/Views/ folder.

  • Navigate to: app/Views
  • Create: message_view.php
  • Add this code:
<!DOCTYPE html>
<html>
<head>
    <title><?= esc($title) ?></title>
</head>
<body>

    <h1><?= esc($title) ?></h1>
    <p><?= esc($message) ?></p>

    <h3>Fruit List:</h3>
    <ul>
        <?php foreach ($items as $item): ?>
            <li><?= esc($item) ?></li>
        <?php endforeach; ?>
    </ul>

</body>
</html>

What’s Happening Here?

  • We’re using esc() to safely output variables (protects against XSS).
  • $title, $message, and $items come from the controller.
  • We loop over the $items array using a foreach loop and render each fruit.

Step 5: Route the Controller

By default, CodeIgniter 4 routes everything to the Home controller. Let’s tell it we now want to use the Message controller.

  • Open the file: app/Config/Routes.php

  • Find this line: $routes->get(‘/’, ‘Home::index’);
  • Add this new route below it: $routes->get(‘message’, ‘Message::index’);

Test it

Now go to: http://localhost:8080/message

You should see:

  • The title “Welcome to CodeIgniter!”
  • A message underneath it
  • A bullet list of fruits: Apple, Banana, Cherry

Awesome. Everything we did so far worked. So now, let’s take things up a notch.

Real Use-Case: Returning a Rendered View for a Product Listing Page

Let’s imagine you’re building a simple eCommerce site. You want to show a list of products on the homepage, grouped by categories, and maybe even include price filters in the future.

To keep it simple for now, we’ll just focus on displaying products by category. You’ll pass this structured data from your controller to the view, and render it dynamically.

Here’s what we’re going to do step-by-step:

Step 1: Update the Controller

We’ll start by editing the same controller you used before (app/Controllers/Message.php). But this time, instead of fruits, we’ll pass in product data grouped by category.

<?php

namespace App\Controllers;

class Message extends BaseController
{
    public function index()
    {
        $data = [
            'title' => 'Product Listing',
            'categories' => [
                'Electronics' => [
                    ['name' => 'Smartphone', 'price' => 699],
                    ['name' => 'Headphones', 'price' => 199],
                ],
                'Books' => [
                    ['name' => 'The Pragmatic Programmer', 'price' => 39],
                    ['name' => 'Clean Code', 'price' => 45],
                ],
                'Clothing' => [
                    ['name' => 'T-shirt', 'price' => 25],
                    ['name' => 'Hoodie', 'price' => 60],
                ]
            ]
        ];

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

What’s Happening Here?

We’re defining an associative array $data that holds:

  • A title
  • A nested array of categories, where each category contains a list of products with names and prices

Then we pass all this data to a view called product_list.

Step 2: Create the View

Now let’s create that new view file.

Go to app/Views/ and create a file called product_list.php.

Here’s the template code:

<!DOCTYPE html>
<html>
<head>
    <title><?= esc($title) ?></title>
</head>
<body>

    <h1><?= esc($title) ?></h1>

    <?php foreach ($categories as $category => $products): ?>
        <h2><?= esc($category) ?></h2>
        <ul>
            <?php foreach ($products as $product): ?>
                <li>
                    <?= esc($product['name']) ?> - $<?= esc($product['price']) ?>
                </li>
            <?php endforeach; ?>
        </ul>
    <?php endforeach; ?>

</body>
</html>

What’s Happening Here?

  • We’re looping through each category and then each product inside that category.
  • esc() is a CodeIgniter helper function that escapes output to prevent XSS attacks.
  • The structure is clean, and any future category or product you add to the controller will render here automatically.

Test it

Now open: http://localhost:8080/message

You should see:

  • A page titled “Product Listing”
  • Products grouped under “Electronics”, “Books”, and “Clothing
  • Each product with its price listed

Success. Instead of passing a simple array of fruits like we did earlier, we’re now passing a structured dataset that resembles what a real eCommerce site might send to its frontend.

Transitioning from Static to Dynamic Data

Up till now, we walked you through how to pass hardcoded data from a controller to a view in CodeIgniter, which is great for grasping the basics. But in practical applications like blogs, dashboards, e-commerce, your data almost always comes from a database.

So let’s build on what we’ve done and take it a step further by pulling data from a database and then passing that into our view.

Here’s how we’ll do this, step by step:

💡 Before you continue:

Open your .env file (you’ll find it in your CodeIgniter project root). If your file is named env, make sure to add . before it. This way CodeIgniter will be able to read it.

Then, in the file, make sure this line is not commented out: CI_ENVIRONMENT = development.

If you see CI_ENVIRONMENT = production, change that to CI_ENVIRONMENT = development.

If it starts with #, remove that. This enables error messages while you’re developing, helpful for catching issues like database connection problems.

Step 1: Set Up Your Database

You’ll need two tables: one for categories, one for products. To do this:

  • Open your XAMPP Control Panel.
  • Start both Apache and MySQL.
  • Then click on “Admin” next to MySQL. This opens phpMyAdmin in your browser.

Once phpMyAdmin is open:

Look at the left sidebar — click “New” at the top.

Under “Create database“, type: ci_store

Make sure the collation is set to utf8mb4_general_ci (this is usually default).

Click “Create“.

Now that your database is created, let’s run the SQL to create your categories and products tables.

In phpMyAdmin, make sure you’ve selected your ci_store database from the left menu.

At the top, click the “SQL” tab.

Paste this SQL:

CREATE TABLE categories (
    id INT AUTO_INCREMENT PRIMARY KEY,
    name VARCHAR(255) NOT NULL
);

CREATE TABLE products (
    id INT AUTO_INCREMENT PRIMARY KEY,
    category_id INT NOT NULL,
    name VARCHAR(255) NOT NULL,
    price DECIMAL(10,2) NOT NULL,
    FOREIGN KEY (category_id) REFERENCES categories(id)
);

Click Go.

That creates both tables. You should see a green success message at the top.

Insert Some Sample Data

In our database table we created, let’s now insert some sample data. Still in the SQL tab, paste this next bit and click Go again:

INSERT INTO categories (name) VALUES (‘Electronics’), (‘Books’), (‘Clothing’);

INSERT INTO products (category_id, name, price) VALUES

(1, ‘Smartphone’, 699),

(1, ‘Headphones’, 199),

(2, ‘The Pragmatic Programmer’, 39),

(2, ‘Clean Code’, 45),

(3, ‘T-shirt’, 25),

(3, ‘Hoodie’, 60);

This just seeds your database with some dummy data to work with. It’s like loading in your first batch of test products and categories.

Time to check if our database is populated correctly. Click on the “categories” table in the left sidebar and then “Browse” at the top. You should see:

  • Electronics
  • Books
  • Clothing

Then do the same with “products”. You’ll see the related product rows.

Now your database is fully set up and ready to be used in CodeIgniter!

Configure Your Codeigniter Database Settings

Open this file:

app/Config/Database.php

Find the $default array and update it to match your database info. Just update these three values in your Database.php file:

‘username’ => ”

‘password’ => ”

‘database’ => ”

So I’ll update my code like so:

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

Make sure these match the values you used in phpMyAdmin otherwise CodeIgniter won’t be able to connect. That is it, now CodeIgniter can talk to your DB.

Step 2: Create the Model

In CodeIgniter, let’s create a model to talk to our database. We’ll create a simple ProductModel.

Create this file: app/Models/ProductModel.php

<?php

namespace App\Models;

use CodeIgniter\Model;

class ProductModel extends Model
{
    protected $table = 'products';
    protected $allowedFields = ['name', 'price', 'category_id'];
    protected $useTimestamps = false;

    public function getProductsGroupedByCategory()
    {
        $builder = $this->db->table('products p');
        $builder->select('p.name as product_name, p.price, c.name as category_name');
        $builder->join('categories c', 'c.id = p.category_id');
        $query = $builder->get();

        $results = [];
        foreach ($query->getResultArray() as $row) {
            $results[$row['category_name']][] = [
                'name' => $row['product_name'],
                'price' => $row['price']
            ];
        }

        return $results;
    }
}

This method gets all products, joins them with their categories, and groups them into an associative array — just like your hardcoded version, but now from the DB.

Step 3: Update the Controller

Now replace the static data in your controller with dynamic data from the model. By that I’m referring to the Message controller file.

<?php

namespace App\Controllers;

use App\Models\ProductModel;

class Message extends BaseController
{
    public function index()
    {
        $productModel = new ProductModel();
        $categories = $productModel->getProductsGroupedByCategory();

        $data = [
            'title' => 'Product Listing',
            'categories' => $categories
        ];

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

Notice that we didn’t need to touch the view at all. That’s the advantage of keeping your logic in the controller — your presentation layer stays clean and reusable, no matter where your data comes from.

Final Check

Open up your browser and go to: http://localhost:8080/message

You should now see the same product listing, but this time it’s 100% dynamic, pulled directly from your database.

Wrapping Up!

Now that you’ve seen how to pass data from a controller to a view in CodeIgniter, you’ve got a solid grip on one of the core concepts behind dynamic web development.

We started with simple messages, moved on to passing full arrays, and finally connected it all to a real MySQL database — showing how to pull live product data and render it on the front end.

If you have any questions, let me know in the comments and I’ll be more than happy to help.

If you’re building something more serious, now’s also a great time to think about performance and hosting, especially for ecommerce-style apps. A fast, scalable host like Cloudways ensures your CodeIgniter app loads fast, even when your product listings get heavy. (Think SSD storage, built-in caching, Cloudflare integration)

Frequently Asked Questions

Q. How to pass data to view in CodeIgniter?

To pass data to a view in CodeIgniter, you use the view() helper and supply the data as an associative array.

$data = ['title' => 'My Page', 'message' => 'Hello World'];
return view('my_view', $data);

This makes $title and $message available inside the my_view.php file.

Q. How to pass data from model to view?

To pass data from a model to a view, first retrieve the data in your controller by calling a model method. Then, pass it to the view like any other array.

$model = new ProductModel();
$products = $model->findAll();

return view('product_list', ['products' => $products]);

The product_list view can now loop through the $products array.

Q. How to display data from a database in CodeIgniter?

To display database data, fetch it using a model in your controller, then pass it to the view. Inside the view, you can echo or loop through the data.

$model = new BlogModel();
$posts = $model->findAll();

return view('blog/index', ['posts' => $posts]);

In the blog/index view, you can use a foreach loop to display each post.

Q. How to pass data between view controllers?

Controllers don’t pass data directly to each other in CodeIgniter. Instead, you should move shared logic or data into a model or service, then access it from any controller that needs it.

If you need to persist data across requests, use sessions:

session()->set('key', 'value'); // Set data
$value = session()->get('key'); // Get data

This allows different controllers or views to access shared values.

Share your opinion in the comment section. COMMENT NOW

Share This Article

Abdul Rehman

Abdul is a tech-savvy, coffee-fueled, and creatively driven marketer who loves keeping up with the latest software updates and tech gadgets. He's also a skilled technical writer who can explain complex concepts simply for a broad audience. Abdul enjoys sharing his knowledge of the Cloud industry through user manuals, documentation, and blog posts.

×

Webinar: How to Get 100% Scores on Core Web Vitals

Join Joe Williams & Aleksandar Savkovic on 29th of March, 2021.

Do you like what you read?

Get the Latest Updates

Share Your Feedback

Please insert Content

Thank you for your feedback!

Do you like what you read?

Get the Latest Updates

Share Your Feedback

Please insert Content

Thank you for your feedback!

Want to Experience the Cloudways Platform in Its Full Glory?

Take a FREE guided tour of Cloudways and see for yourself how easily you can manage your server & apps on the leading cloud-hosting platform.

Start my tour