CodeIgniter

Contoh CRUD CodeIgniter 4 dan MySQL Lengkap

Panduan lengkap membuat CRUD produk CodeIgniter 4 dan MySQL dengan migration, seeder, validasi, pencarian, pagination, dan Bootstrap.

Contoh coding Contoh CRUD CodeIgniter 4 dan MySQL Lengkap
Langkah 7 dari 11

Membuat Controller Products

Buat app/Controllers/Products.php. Controller lengkap sudah tersedia dalam source code unduhan. Struktur method utamanya:

class Products extends BaseController
{
    private ProductModel $products;

    public function __construct()
    {
        helper(['form', 'url']);
        $this->products = new ProductModel();
    }

    public function index(): string
    {
        $keyword = trim((string) $this->request->getGet('keyword'));
        $query = $this->products;

        if ($keyword !== '') {
            $query = $query->groupStart()
                ->like('name', $keyword)
                ->orLike('sku', $keyword)
                ->groupEnd();
        }

        return view('products/index', [
            'title' => 'Data Produk',
            'products' => $query->orderBy('id', 'DESC')->paginate(10),
            'pager' => $this->products->pager,
            'keyword' => $keyword,
        ]);
    }
}

Untuk menyimpan data, ambil hanya field yang memang dibutuhkan:

$data = [
    'sku' => strtoupper(trim((string) $this->request->getPost('sku'))),
    'name' => trim((string) $this->request->getPost('name')),
    'price' => $this->request->getPost('price'),
    'stock' => $this->request->getPost('stock'),
    'description' => trim((string) $this->request->getPost('description')),
];

Validasi SKU saat menambah dan mengedit berbeda. Saat mengedit, ID produk aktif harus dikecualikan:

// Tambah
'sku' => 'required|max_length[40]|is_unique[products.sku]'

// Edit
'sku' => "required|max_length[40]|is_unique[products.sku,id,{$id}]"

Jika validasi gagal, kembalikan input dan daftar error:

return redirect()->back()
    ->withInput()
    ->with('errors', $this->validator->getErrors());