Berikut adalah tutorial CRUD di CodeIgniter 4 dengan gambar. Tutorial ini akan menggunakan Bootstrap untuk tampilan dan MySQL sebagai database.
1. Persiapan Project dan Database
Instalasi CodeIgniter 4
Download CodeIgniter 4 atau instal dengan Composer:
composer create-project codeigniter4/appstarter ci4_crud_images
Konfigurasi Database
Buat database MySQL ci4_crud_images dan sesuaikan app/Config/Database.php:
public $default = [
'DSN' => '',
'hostname' => 'localhost',
'username' => 'root',
'password' => '',
'database' => 'ci4_crud_images',
'DBDriver' => 'MySQLi',
];
Membuat Tabel Database
Kita akan buat tabel menggunakan migration, buka cmd lalu klik berikut:
php spark make:migration CreateProductsTable
Setelah menjalankan perintah tersebut, file migration akan dibuat di app/Database/Migrations. Buka file dengan nama seperti 2024-11-07-000000_CreateProductsTable.php, lalu edit dengan kode berikut:
<?php
namespace App\Database\Migrations;
use CodeIgniter\Database\Migration;
class CreateProductsTable extends Migration
{
public function up()
{
$this->forge->addField([
'id' => [
'type' => 'INT',
'constraint' => 11,
'unsigned' => true,
'auto_increment' => true,
],
'name' => [
'type' => 'VARCHAR',
'constraint' => '255',
],
'description' => [
'type' => 'TEXT',
'null' => true,
],
'price' => [
'type' => 'DECIMAL',
'constraint' => '10,2',
],
'image' => [
'type' => 'VARCHAR',
'constraint' => '255',
'null' => true,
],
'created_at' => [
'type' => 'DATETIME',
'null' => true,
],
'updated_at' => [
'type' => 'DATETIME',
'null' => true,
],
]);
$this->forge->addKey('id', true);
$this->forge->createTable('products');
}
public function down()
{
$this->forge->dropTable('products');
}
}
Jalankan migration:
php spark migrate
Atau tanpa migration, Buat tabel products dengan kolom image untuk menyimpan path gambar seperti berikut:
CREATE TABLE `products` (
`id` INT(11) NOT NULL AUTO_INCREMENT,
`name` VARCHAR(255) NOT NULL,
`description` TEXT NOT NULL,
`price` DECIMAL(10, 2) NOT NULL,
`image` VARCHAR(255),
`created_at` TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
PRIMARY KEY (`id`)
);
2. Membuat Model untuk CRUD
Buat file ProductModel.php di app/Models:
<?php
namespace App\Models;
use CodeIgniter\Model;
class ProductModel extends Model
{
protected $table = 'products';
protected $primaryKey = 'id';
protected $allowedFields = ['name', 'description', 'price', 'image'];
}
3. Membuat Controller untuk CRUD dengan Gambar
Buat file ProductController.php di app/Controllers:
<?php
namespace App\Controllers;
use App\Models\ProductModel;
use CodeIgniter\Controller;
class ProductController extends Controller
{
public function index()
{
$model = new ProductModel();
$data['products'] = $model->findAll();
return view('products/index', $data);
}
public function create()
{
return view('products/create');
}
public function store()
{
$model = new ProductModel();
$file = $this->request->getFile('image');
$imageName = '';
if ($file->isValid() && !$file->hasMoved()) {
$imageName = $file->getRandomName();
$file->move('uploads', $imageName);
}
$data = [
'name' => $this->request->getPost('name'),
'description' => $this->request->getPost('description'),
'price' => $this->request->getPost('price'),
'image' => $imageName,
];
$model->insert($data);
return redirect()->to('/products');
}
public function edit($id)
{
$model = new ProductModel();
$data['product'] = $model->find($id);
return view('products/edit', $data);
}
public function update($id)
{
$model = new ProductModel();
$file = $this->request->getFile('image');
$product = $model->find($id);
$imageName = $product['image'];
if ($file->isValid() && !$file->hasMoved()) {
if ($imageName && file_exists("uploads/$imageName")) {
unlink("uploads/$imageName");
}
$imageName = $file->getRandomName();
$file->move('uploads', $imageName);
}
$data = [
'name' => $this->request->getPost('name'),
'description' => $this->request->getPost('description'),
'price' => $this->request->getPost('price'),
'image' => $imageName,
];
$model->update($id, $data);
return redirect()->to('/products');
}
public function delete($id)
{
$model = new ProductModel();
$product = $model->find($id);
if ($product['image'] && file_exists("uploads/{$product['image']}")) {
unlink("uploads/{$product['image']}");
}
$model->delete($id);
return redirect()->to('/products');
}
}
4. Membuat Views dengan Bootstrap
Tampilan Daftar Produk (index.php)
Buat folder app/Views/products dan file index.php:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Daftar Produk</title>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.css">
</head>
<body>
<div class="container mt-5">
<h2>Daftar Produk</h2>
<a href="/products/create" class="btn btn-primary mb-3">Tambah Produk</a>
<table class="table table-bordered">
<thead>
<tr>
<th>ID</th>
<th>Nama</th>
<th>Deskripsi</th>
<th>Harga</th>
<th>Gambar</th>
<th>Aksi</th>
</tr>
</thead>
<tbody>
<?php foreach ($products as $product): ?>
<tr>
<td><?= $product['id'] ?></td>
<td><?= $product['name'] ?></td>
<td><?= $product['description'] ?></td>
<td><?= $product['price'] ?></td>
<td><img src="/uploads/<?= $product['image'] ?>" width="100"></td>
<td>
<a href="/products/edit/<?= $product['id'] ?>" class="btn btn-warning">Edit</a>
<a href="/products/delete/<?= $product['id'] ?>" class="btn btn-danger" onclick="return confirm('Yakin ingin menghapus?')">Hapus</a>
</td>
</tr>
<?php endforeach; ?>
</tbody>
</table>
</div>
</body>
</html>
4.2 Tampilan Tambah Produk (create.php)
Buat file create.php di app/Views/products untuk menambahkan data dan gambar:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Tambah Produk</title>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.css">
</head>
<body>
<div class="container mt-5">
<h2>Tambah Produk</h2>
<form action="/products/store" method="post" enctype="multipart/form-data">
<div class="form-group">
<label>Nama Produk:</label>
<input type="text" class="form-control" name="name" required>
</div>
<div class="form-group">
<label>Deskripsi:</label>
<textarea class="form-control" name="description" required></textarea>
</div>
<div class="form-group">
<label>Harga:</label>
<input type="number" class="form-control" name="price" required>
</div>
<div class="form-group">
<label>Gambar:</label>
<input type="file" class="form-control" name="image" required>
</div>
<button type="submit" class="btn btn-primary">Simpan</button>
</form>
</div>
</body>
</html>
4.3 Tampilan Edit Produk (edit.php)
Buat file edit.php di app/Views/products:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Edit Produk</title>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.css">
</head>
<body>
<div class="container mt-5">
<h2>Edit Produk</h2>
<form action="/products/update/<?= $product['id'] ?>" method="post" enctype="multipart/form-data">
<div class="form-group">
<label>Nama Produk:</label>
<input type="text" class="form-control" name="name" value="<?= $product['name'] ?>" required>
</div>
<div class="form-group">
<label>Deskripsi:</label>
<textarea class="form-control" name="description" required><?= $product['description'] ?></textarea>
</div>
<div class="form-group">
<label>Harga:</label>
<input type="number" class="form-control" name="price" value="<?= $product['price'] ?>" required>
</div>
<div class="form-group">
<label>Gambar Saat Ini:</label><br>
<?php if ($product['image']): ?>
<img src="/uploads/<?= $product['image'] ?>" width="100" class="mb-2">
<?php else: ?>
<p>Tidak ada gambar</p>
<?php endif; ?>
<label>Gambar Baru (jika ingin mengubah):</label>
<input type="file" class="form-control" name="image">
</div>
<button type="submit" class="btn btn-primary">Update</button>
<a href="/products" class="btn btn-secondary">Batal</a>
</form>
</div>
</body>
</html>
5. Routing
Tambahkan route berikut di app/Config/Routes.php:
$routes->get('/products', 'ProductController::index');
$routes->get('/products/create', 'ProductController::create');
$routes->post('/products/store', 'ProductController::store');
$routes->get('/products/edit/(:num)', 'ProductController::edit/$1');
$routes->post('/products/update/(:num)', 'ProductController::update/$1');
$routes->get('/products/delete/(:num)', 'ProductController::delete/$1');
6. Testing
Akses /products di browser, tambahkan, edit, dan hapus produk beserta gambarnya.
http://localhost:8080/products/create
http://localhost:8080/products
http://localhost:8080/products/edit/1
Selamat mencoba!! Silahkan tinggalkan komentar jika ada yang masih belum berhasil.
Terimakasih :)