Getting Started with Models
Revision: 2025/10/13
This tutorial will guide you through the basic operations to create and use a Model in MilkAdmin: from table creation to data insertion, reading, updating, and deletion.
- Create a Model and define the table schema
- Automatically generate the table in the database
- Insert new records (CREATE)
- Read data (READ)
- Update existing records (UPDATE)
- Delete records (DELETE)
- Drop a table
1. Creating a Model
A Model represents a table in the database. Let's start by creating a simple Model to manage products:
use App\Abstracts\AbstractModel;
class ProductModel extends AbstractModel {
protected function configure($rule): void {
$rule->table('#__products')
->id()
->string('name', 100)->required()
->decimal('price', 10, 2)->default(0)
->text('description')->nullable()
->boolean('in_stock')->default(true)
->datetime('created_at')->nullable();
}
}
->id()- Creates an auto-incrementidcolumn as primary key->string('name', 100)- VARCHAR field of 100 characters->decimal('price', 10, 2)- DECIMAL field for prices (10 total digits, 2 decimals)->text('description')- TEXT field for long descriptions->boolean('in_stock')- Boolean field (TINYINT)->datetime('created_at')- DATETIME field for dates->nullable()- Allows NULL values->required()- Required field (NOT NULL)->default()- Default value
2. Creating the Table
Once the Model is defined, you need to create the table in the database. The recommended way is to use CLI commands:
Recommended Method: CLI Commands
First module installation:
php milkadmin/cli.php products:install
This command creates the table and executes afterCreateTable() to insert initial data.
After Model schema changes:
php milkadmin/cli.php products:update
This command updates the table structure without executing afterCreateTable().
Important
Table creation/update is NOT automatic! After creating or modifying a Model, you must always manually run the CLI install or update command.
Alternative Method: buildTable() via Code
For quick tests or special situations, you can call buildTable() directly in your code:
$products = new ProductModel();
// Create the table if it doesn't exist, or update it if it does
if ($products->buildTable()) {
echo "Table created/updated successfully!";
} else {
echo "Error: " . $products->getLastError();
}
Note: The buildTable() method is smart: if the table doesn't exist it creates it (and executes afterCreateTable()), if it already exists it automatically updates it to reflect any schema changes (without executing afterCreateTable()).
When to use buildTable() in code
Use buildTable() via code only for:
- Testing and rapid development
- Custom installation scripts
- Modules that create tables dynamically
For production modules, always use CLI commands!
3. Inserting Data (CREATE)
To insert a new record use the store() method:
if(!$products->store([
'name' => 'Laptop Pro',
'price' => 1299.99,
'description' => 'High-performance laptop',
'in_stock' => true,
'created_at' => date('Y-m-d H:i:s')
])) {
MessagesHandler::addError($products->getLastError());
}
4. Reading Data (READ)
Reading all records
$result = $products->getAll();
echo "Found " . $result->count() . " products:\n";
while ($result->hasNext()) {
echo "- " . $result->name . ": €" . $result->price . "\n";
$result->next();
}
Reading a single record by ID
$product = $products->getById(1);
if (!$product->isEmpty()) {
echo "Name: " . $product->name;
echo "Price: €" . $product->price;
}
Reading multiple records
$products = $products->getByIds([1, 2, 3]);
Query with conditions
// Find available products with price < 100
$list_of_products = $products->where('in_stock = ?', [true])
->where('price < ?', [100])
->order('price', 'asc')
->getResults();
foreach ($list_of_products as $product) {
echo $product->name . ": €" . $product->price . "\n";
}
// Find available products with price < 100
$singleProduct = $products->where('in_stock = ?', [true])
->where('price < ?', [100])
->order('price', 'asc')
->getRow();
echo $singleProduct->name . ": €" . $singleProduct->price;
5. Updating Data (UPDATE)
To update an existing record, pass the ID as the second parameter to store():
$update_data = [
'price' => 1199.99,
'description' => 'High-performance laptop - SALE!'
];
$result = $products->store($update_data, 1);
}
6. Deleting Data (DELETE)
To delete a record use the delete() method:
$result = $products->delete(1);
if ($result) {
echo "Product deleted!";
echo "Remaining products: " . $products->total();
} else {
echo "Error: " . $products->getLastError();
}
7. Dropping the Table
To completely remove the table from the database:
$result = $products->dropTable();
if ($result) {
echo "Table dropped successfully!";
}
8. Installing the table
To install or update the tables of a module you are creating, you can use:
php milkadmin/cli.php module:install
php milkadmin/cli.php module:update
Next Steps
To learn more:
- Abstract Model - Complete Model documentation
- Query Builder - Advanced and complex queries
- Schema - Advanced table management