Advertisement
Google Ad Slot: content-top
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
Using a Model in a Controller
File: app/Controllers/Product.php
Setting Up the Route
To access the controller methods, you must define routes.
File: app/Config/Routes.php
- Visiting
/products→ CallsProduct::index()→ Fetches data from Model → Passes it to View. - Submitting product form to
/products/save→ CallsProduct::saveProduct()→ Saves to database.
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.