CodeIgniter Model

What is a Model?

In CodeIgniter, a Model is a PHP class that interacts with your database.

It is responsible for:

  • Retrieving data
  • Inserting new data
  • Updating existing data
  • Deleting data

Think of the Model as the database handler in your application.

It does not deal with HTML or user interface — only data logic.

Where Models Live in CodeIgniter

Models are stored in:

app/Models/

Each model usually corresponds to a specific database table.

Creating a Model in CodeIgniter

Example: ProductModel for products table

File: app/Models/ProductModel.php

Example
<?php

namespace App\Models;
use CodeIgniter\Model;

class ProductModel extends Model
{
protected $table = 'products'; // Table name
protected $primaryKey = 'id'; // Primary key column

// Columns that can be inserted/updated
protected $allowedFields = ['name', 'price', 'description'];

// Return results as arrays
protected $returnType = 'array';
}

Using a Model in a Controller

File: app/Controllers/Product.php

Example
<?php

namespace App\Controllers;
use App\Models\ProductModel;

class Product extends BaseController
{
public function index()
{
$productModel = new ProductModel();
// Get all products
$data['products'] = $productModel->findAll();

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

public function saveProduct()
{
$productModel = new ProductModel();

$productModel->save([
'name' => 'New Product',
'price' => 99,
'description' => 'This is a sample product.'
]);

return redirect()->to('/products');
}
}

Common Model Methods in CodeIgniter

Method

Description

Example

findAll()

Get all rows

$model->findAll();

find($id)

Get a single row by primary key

$model->find(1);

where()

Add WHERE condition

$model->where('price >', 50)->findAll();

save()

Insert or update

Insert or update

insert()

Insert new row

$model->insert($data);

update()

Update a row

$model->update($id, $data);

delete()

Delete a row

$model->delete($id);

Passing Data from Model → Controller → View

Flow:

Model → Controller → View

Example:

// Controller
$productModel = new ProductModel();
$data['products'] = $productModel->findAll();
return view('products_list', $data);


Advantages of Using Models

  • Keeps database logic separate from controllers & views.
  • Cleaner, more maintainable code.
  • Built-in query methods (no need to write raw SQL every time).
  • Secure: Prevents mass assignment vulnerabilities using $allowedFields.



Whereisstuff is simple learing platform for beginer to advance level to improve there skills in technologies.we will provide all material free of cost.you can write a code in runkit workspace and we provide some extrac features also, you agree to have read and accepted our terms of use, cookie and privacy policy.
© Copyright 2024 www.whereisstuff.com. All rights reserved. Developed by whereisstuff Tech.