Membuat CRUD Article di codeigniter, Oke kita lanjutkan tutorial membuat web dengan menggunakan codeigniter. Sekarang kita akan membuat CRUD Artikel dalam artikel kita akan menggabungkan beberapa tabel seperti, tabel category, dan tabel user. Oke kita akan langsung aja buat kodingnya. Jika kalian baru saja menemukan artikel ini silahkan baca artikel sebelumnya agar bisa lebih paham.
Membuat CRUD Article di codeigniter
Silahkan kalian buka folder application/controller/admin lalu buka file Article.php, ganti semua dengan kode di bawah ini :
<?php
defined('BASEPATH') or exit('No direct script access allowed');
class Article extends CI_Controller
{
//load data
public function __construct()
{
parent::__construct();
$this->load->helper('string');
$this->load->model('article_model');
$this->load->model('category_model');
}
//listing data Post Article
public function index()
{
$article = $this->article_model->get_all();
$data = array(
'title' => 'Data Article',
'article' => $article,
'content' => 'backend/article/get_article'
);
$this->load->view('backend/layout/wrapp', $data, FALSE);
}
//Create New Artice
public function create()
{
$category = $this->category_model->get_all();
$valid = $this->form_validation;
$valid->set_rules(
'title',
'Judul Artikel',
'required',
array(
'required' => '%s Harus Di isi',
)
);
$valid->set_rules(
'title',
'Judul Artikel',
'required',
array(
'required' => '%s Harus Di isi',
)
);
$valid->set_rules(
'content',
'Konten Artikel',
'required',
array(
'required' => '%s Harus Di isi',
)
);
$valid->set_rules(
'article_status',
'Status',
'required',
array(
'required' => '%s Harus Di isi',
)
);
$valid->set_rules(
'category_id',
'Kategori',
'required',
array(
'required' => '%s Harus Di isi',
)
);
if ($valid->run()) {
$config['upload_path'] = './assets/uploads/images/';
//Gambar Artikel akan disimpan di folder assets/uploads/images
//Pastikan kamu sudah membuat folder di atas
$config['allowed_types'] = 'gif|jpg|png|jpeg'; //tipe file yang di dukung
$config['max_size'] = 5000; //ukuran file dalam Kilobyte
$config['max_width'] = 5000; //Lebar (pixel)
$config['max_height'] = 5000; //tinggi (pixel)
$this->load->library('upload', $config);
if (!$this->upload->do_upload('image')) {
//Jika Validasi Gagal tampilkan error disini
$data = array(
'title' => 'Create New Article',
'error_upload' => $this->upload->display_errors(),
'category' => $category,
'content' => 'backend/article/create'
);
$this->load->view('backend/layout/wrapp', $data, FALSE);
} else {
//Jika validasi berhasil maka
//Buat variable data upload image
$upload_data = array('uploads' => $this->upload->data());
// Ambil data dari inputan create article
$article_slug = url_title($this->input->post('title'), 'dash', TRUE);
$slug_unik = random_string('numeric', 5);
$data = array(
'user_id' => $this->session->userdata('id'),
'category_id' => $this->input->post('category_id'),
'title' => $this->input->post('title'),
'article_slug' => $article_slug . '-' . $slug_unik,
'content' => $this->input->post('content'),
'image' => $upload_data['uploads']['file_name'],
'article_status' => $this->input->post('article_status'),
'keywords' => $this->input->post('keywords'),
'created_at' => date('Y-m-d H:i:s'),
'updated_at' => date('Y-m-d H:i:s')
);
//lalu kirim ke database melalui model di bawah ini
$this->article_model->create($data);
//Jika berhasil tampilkan pesan berhasil
$this->session->set_flashdata('sukses', 'Artikel telah ditambahkan');
//Lalu redirect ke halaman list article
redirect(base_url('admin/article'), 'refresh');
}
}
//Proses pengiriman ke database selesai
//Menampilkan halaman create article
$data = array(
'title' => 'Create New Article',
'category' => $category,
'content' => 'backend/article/create'
);
$this->load->view('backend/layout/wrapp', $data, FALSE);
}
//Fungsi untuk mengubah data article
public function update($id)
{
//Ambil id article yang akan di ubah
$article = $this->article_model->detail($id);
$category = $this->category_model->get_all();
//Validasi form
$valid = $this->form_validation;
$valid->set_rules(
'title',
'Judul Artikel',
'required',
array(
'required' => '%s Harus Di isi',
)
);
$valid->set_rules(
'title',
'Judul Artikel',
'required',
array(
'required' => '%s Harus Di isi',
)
);
$valid->set_rules(
'content',
'Konten Artikel',
'required',
array(
'required' => '%s Harus Di isi',
)
);
$valid->set_rules(
'article_status',
'Status',
'required',
array(
'required' => '%s Harus Di isi',
)
);
$valid->set_rules(
'category_id',
'Kategori',
'required',
array(
'required' => '%s Harus Di isi',
)
);
if ($valid->run()) {
//Jika Gambar tidak di ganti
if (!empty($_FILES['image']['name'])) {
$config['upload_path'] = './assets/uploads/images/';
//Gambar akan disimpan di folder assets/uploads/images
//Pastikan kamu sudah membuat folder di atas
$config['allowed_types'] = 'gif|jpg|png|jpeg';
$config['max_size'] = 5000; //Dalam Kilobyte
$config['max_width'] = 5000; //Lebar (pixel)
$config['max_height'] = 5000; //tinggi (pixel)
$this->load->library('upload', $config);
if (!$this->upload->do_upload('image')) {
//Jika validasi gagal tampilkan data berdasarkan id article yang di pilih
$data = array(
'title' => 'Update Article: ' . $article->title,
'article' => $article,
'category' => $category,
'error_upload' => $this->upload->display_errors(),
'content' => 'backend/article/update'
);
$this->load->view('backend/layout/wrapp', $data, FALSE);
} else {
//Jika validasi berhasil maka
$upload_data = array('uploads' => $this->upload->data());
//Gambar akan disimpan di folder assets/uploads/images
//Pastikan kamu sudah membuat folder di atas
// Hapus Gambar Lama Jika ada foto baru yang di upload
if ($article->image != "") {
unlink('./assets/uploads/images/' . $article->image);
}
//Proses penghapusan selesai
//lalu ambil data yang dikirim melalui form update Article
$data = array(
'id' => $id,
'user_id' => $this->session->userdata('id'),
'category_id' => $this->input->post('category_id'),
'title' => $this->input->post('title'),
'content' => $this->input->post('content'),
'image' => $upload_data['uploads']['file_name'],
'article_status' => $this->input->post('article_status'),
'keywords' => $this->input->post('keywords'),
'updated_at' => date('Y-m-d H:i:s')
);
//Proses Update data ke database
$this->article_model->update($data);
//Jika berhasil tampilkan pesan
$this->session->set_flashdata('message', 'article <b>' . $article->title . '</b> telah di Update');
redirect(base_url('admin/article'), 'refresh');
}
} else {
//Jika Update data Article tanpa mengupload Gambar
$i = $this->input;
// Hapus Gambar Lama Jika ada upload foto baru
if ($article->image != "")
$data = array(
'id' => $id,
'user_id' => $this->session->userdata('id'),
'category_id' => $this->input->post('category_id'),
'title' => $this->input->post('title'),
'content' => $this->input->post('content'),
'article_status' => $this->input->post('article_status'),
'keywords' => $this->input->post('keywords'),
'updated_at' => date('Y-m-d H:i:s')
);
$this->article_model->update($data);
$this->session->set_flashdata('message', 'Article <b> ' . $article->title . ' </b>telah diubah');
redirect(base_url('admin/article'), 'refresh');
}
}
//Proses Masuk database Selesai
$data = array(
'title' => 'Update Article ' . $article->title,
'article' => $article,
'category' => $category,
'content' => 'backend/article/update'
);
$this->load->view('backend/layout/wrapp', $data, FALSE);
}
//Fungsi delete article
public function delete($id)
{
//Cek user apakah sudah login
$this->cek_login->cek();
$article = $this->article_model->detail($id);
//Menghapus gambar
if ($article->image != "") {
unlink('./assets/uploads/images/' . $article->image);
}
//Penghapusan gambar selesai
$data = array(
'id' => $article->id
);
$this->article_model->delete($data);
$this->session->set_flashdata('message', 'Article <b>' . $article->title . '</b> telah di Hapus');
redirect(base_url('admin/article'), 'refresh');
}
}
Lalu sekarang kita akan buat model untuk artikel ini, silahkan kalian buka folder models yang berada di application/models lalu buat sebuah file Article_model.php lalu paste kode berikut ini :
<?php
defined('BASEPATH') or exit('No direct script access allowed');
class Article_model extends CI_Model
{
//load database
public function __construct()
{
parent::__construct();
$this->load->database();
}
//Ambil semua data article
public function get_all()
{
$this->db->select('article.*, category.category_name, user.name');
$this->db->from('article');
//join dengan tabel category
$this->db->join('category', 'category.id = article.category_id', 'LEFT');
$this->db->join('user', 'user.id = article.user_id', 'LEFT');
$this->db->order_by('id', 'DESC');
$query = $this->db->get();
return $query->result();
}
//Detail data article berdasarkan id
public function detail($id)
{
$this->db->select('*');
$this->db->from('article');
$this->db->where('id', $id);
$query = $this->db->get();
return $query->row();
}
//Menambahkan data
public function create($data)
{
$this->db->insert('article', $data);
}
//Mengubah data
public function update($data)
{
$this->db->where('id', $data['id']);
$this->db->update('article', $data);
}
//Menghapus Data
public function delete($data)
{
$this->db->where('id', $data['id']);
$this->db->delete('article', $data);
}
}
Pada model artikel ini kita melakukan join category dan user dengan tujuan untuk meanmpilkan nama category dan nama user sebagai author artikel. Sekarang kita akan membuat tampilan di halaman adminnya. silahkan kalian beralih ke folder views yang berada di application/views lalu buka lagi folder backend kemudian buka file get_article.php yang sebelumnya sudah pernah kita buat, lalu ubah semua kode dengan kode kode php di bawah ini :
<div class="d-sm-flex align-items-center justify-content-between mb-4">
<h1 class="h3 mb-0 text-gray-800"><?php echo $title; ?></h1>
<a href="<?php echo base_url('admin/article/create'); ?>" class="btn btn-primary btn-icon-split">
<span class="icon text-white-50">
<i class="fas fa-newspaper"></i>
</span>
<span class="text">Tambah Article</span>
</a>
</div>
<?php
if ($this->session->flashdata('message')) {
echo '<div class="alert alert-success">';
echo $this->session->flashdata('message');
echo '</div>';
}
?>
<div class="card shadow mb-4">
<div class="card-body">
<div class="table-responsive">
<table class="table table-bordered" id="dataTable" width="100%" cellspacing="0">
<thead>
<tr>
<th width="5%">No</th>
<th>Judul</th>
<th>Category</th>
<th>Author</th>
<th>Status</th>
<th width="20%">Aksi</th>
</tr>
</thead>
<tbody>
<?php $i = 1;
foreach ($article as $article) { ?>
<tr>
<td><?php echo $i; ?></td>
<td><?php echo $article->title; ?></td>
<td><?php echo $article->category_name; ?></td>
<td><?php echo $article->name; ?></td>
<td>
<?php if ($article->article_status == 'Publish') { ?>
<span class="badge badge-info p-2">Publish</span>
<?php } else { ?>
<span class="badge badge-secondary p-2">Draft</span>
<?php } ?>
</td>
<td>
<a href="<?php echo base_url('admin/article/update/' . $article->id); ?> " class="btn btn-success btn-sm"><i class="fas fa-user-edit"></i> Edit</a>
<?php
include('delete.php');
?>
<a href='#' class="btn btn-primary btn-sm"><i class="fas fa-eye"></i> View</a>
</td>
</tr>
<?php $i++;
} ?>
</tbody>
</table>
</div>
</div>
</div>
Jika sudah simpan file, Sekarang kita akan membuat file untuk menambahkan artikel, Masih di folder article, silahkan buat sebuah file create.php lalu copy code di bawah ini :
<?php echo form_open_multipart(base_url('admin/article/create')); ?>
<div class="row">
<div class="col-md-8">
<div class="card shadow mb-4">
<div class="card-header">
Create New Article
</div>
<div class="card-body">
<div class="row">
<div class="col-md-3">
<label>Title <span class="text-danger">*</span></label>
</div>
<div class="col-md-9">
<div class="form-group">
<input type="text" class="form-control" name="title" value="<?php echo set_value('title') ?>">
<?php echo form_error('title', '<span class="text-danger">', '</span>'); ?>
</div>
</div>
<div class="col-md-3">
<label>Category <span class="text-danger">*</span></label>
</div>
<div class="col-md-9">
<div class="form-group">
<select name="category_id" class="form-control">
<option></option>
<?php foreach ($category as $category) { ?>
<option value="<?php echo $category->id; ?>"><?php echo $category->category_name; ?></option>
<?php } ?>
</select>
<?php echo form_error('category_id', '<span class="text-danger">', '</span>'); ?>
</div>
</div>
<div class="col-md-3">
<label>Konten <span class="text-danger">*</span></label>
</div>
<div class="col-md-9">
<div class="form-group">
<textarea class="form-control" name="content" id="editor" value="<?php echo set_value('content') ?>"></textarea>
<?php echo form_error('content', '<span class="text-danger">', '</span>'); ?>
</div>
</div>
<div class="col-md-3">
<label>Keywords <span class="text-danger">*</span></label>
</div>
<div class="col-md-9">
<div class="form-group">
<input type="text" class="form-control" name="keywords" value="<?php echo set_value('keywords') ?>">
<?php echo form_error('keywords', '<span class="text-danger">', '</span>'); ?>
</div>
</div>
</div>
</div>
</div>
</div>
<div class="col-md-4">
<div class="card shadow mb-4">
<div class="card-header">
Options
</div>
<div class="card-body">
<label>Status <span class="text-danger">*</span></label>
<div class="form-group">
<select name="article_status" class="form-control">
<option value="Publish">Publish</option>
<option value="Draft">Draft</option>
</select>
<?php echo form_error('article_status', '<span class="text-danger">', '</span>'); ?>
</div>
<label>Upload Gambar <span class="text-danger">*</span></label>
<div class="form-group">
<input type="file" name="image">
</div>
<div class="form-group">
<button type="submit" name="submit" class="btn btn-primary btn-lg"><i class="fa fa-save"></i> Publish</button>
</div>
</div>
</div>
</div>
</div>
<?php echo form_close(); ?>
Kemudian simpan file, Sekarang kita akan membuat file untuk mengupdate artikel silahkan buat file update.php masih di folder article lalu copy code di bawah ini :
<?php echo form_open_multipart(base_url('admin/article/update/' . $article->id)); ?>
<div class="row">
<div class="col-md-8">
<div class="card shadow mb-4">
<div class="card-header">
<?php echo $title; ?>
</div>
<div class="card-body">
<div class="row">
<div class="col-md-3">
<label>Title <span class="text-danger">*</span></label>
</div>
<div class="col-md-9">
<div class="form-group">
<input type="text" class="form-control" name="title" value="<?php echo $article->title; ?>">
<?php echo form_error('title', '<span class="text-danger">', '</span>'); ?>
</div>
</div>
<div class="col-md-3">
<label>Category <span class="text-danger">*</span></label>
</div>
<div class="col-md-9">
<div class="form-group">
<select name="category_id" class="form-control">
<option></option>
<?php foreach ($category as $category) { ?>
<option value="<?php echo $category->id; ?>" <?php if ($article->category_id == $category->id) {
echo "selected";
} ?>>
<?php echo $category->category_name; ?>
</option>
<?php } ?>
</select>
<?php echo form_error('category_id', '<span class="text-danger">', '</span>'); ?>
</div>
</div>
<div class="col-md-3">
<label>Konten <span class="text-danger">*</span></label>
</div>
<div class="col-md-9">
<div class="form-group">
<textarea class="form-control" name="content" id="editor" value="<?php echo $article->content; ?>"><?php echo $article->content; ?></textarea>
<?php echo form_error('content', '<span class="text-danger">', '</span>'); ?>
</div>
</div>
<div class="col-md-3">
<label>Keywords <span class="text-danger">*</span></label>
</div>
<div class="col-md-9">
<div class="form-group">
<input type="text" class="form-control" name="keywords" value="<?php echo $article->keywords; ?>">
<?php echo form_error('keywords', '<span class="text-danger">', '</span>'); ?>
</div>
</div>
</div>
</div>
</div>
</div>
<div class="col-md-4">
<div class="card shadow mb-4">
<div class="card-header">
Options
</div>
<div class="card-body">
<label>Status <span class="text-danger">*</span></label>
<div class="form-group">
<select name="article_status" class="form-control">
<option value="Publish" <?php if ($article->article_status == "Publish") {
echo "selected";
} ?>>Publish</option>
<option value="Draft">Draft</option>
</select>
<?php echo form_error('article_status', '<span class="text-danger">', '</span>'); ?>
</div>
<label>Chane Image <span class="text-danger">*</span></label>
<div class="form-group">
<input type="file" name="image"><br>
<img class="img img-fluid" src="<?php echo base_url('assets/uploads/images/' . $article->image); ?>">
</div>
<div class="form-group">
<button type="submit" name="submit" class="btn btn-primary btn-lg"><i class="fa fa-save"></i> Publish</button>
</div>
</div>
</div>
</div>
</div>
<?php echo form_close(); ?>
Lalu simpan File kemudian yang terakhir kita akan membuat file delete silahkan buat file dengan nama delete.php lalu copy kode di bawah ini :
<button type="button" class="btn btn-danger btn-sm" data-toggle="modal" data-target="#Delete<?php echo $article->id; ?>">
<i class="fa fa-close"></i> Hapus
</button>
<div class="modal fade" id="Delete<?php echo $article->id; ?>">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<h6 class="modal-title"> Menghapus Data</h6>
<button type="button" class="close" data-dismiss="modal" aria-label="Close">
<span aria-hidden="true"><i class="fa fa-window-close"></i></span></button>
</div>
<div class="modal-body">
<p>Apakah Anda Yakin Ingin Menghapus Data Artkel <b><?php echo $article->title ?></b>?</p>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-primary pull-left" data-dismiss="modal"><i class="fa fa-close"></i> Batal</button>
<a href="<?php echo base_url('admin/article/delete/' . $article->id) ?>" class="btn btn-danger pull-right"><i class="fa fa-close"></i> Ya, Hapus Artikel</a>
</div>
</div>
</div>
</div>
Jika sudah silahkan simpan file, Sekarang silahkan anda jalankan dengan mengakses http://localhost/belajarweb/admin/article, jika kamu belum login kamu akan di redirect ke halaman auth. jika fungsi sudah bisa di jalankan, kita akan lanjutkan membuat tampilan frontend sehingga kita bisa menampilkan semua konten kita ke para pembaca. Oke sampai ketemu lagi di artikel selanjutnya.