Tutorial Membuat CRUD user di framework codeigniter

  • Whatsapp
Tutorial Membuat CRUD

Tutorial Membuat CRUD user di framework codeigniter, Oke kita lanjutkan tutorial membuat web dengan codeigniter, sekarang kita akan membuat CRUD User, dan nantinya user di gunakan untuk login ke admin panel. Kita langsung saja silahkan kalian buka projek kalian kalau kalian mengikuti sesuai dengan tutorial ini, nama projeknya adalah belajarweb. Jika kalian baru menemukan artikel ini silahkan baca tutorial membuat web dengan codeigniter dari awal ya biar nggak bingung.

Silahkan buka folder application/controllers/admin lalu buat file dengan nama User.php kemudian copy code di bawah ini :

<?php
defined('BASEPATH') or exit('No direct script access allowed');

class User extends CI_Controller
{
//load data yang di butuhkan, jika sudah ada di autoload maka tidak perlu diload lagi
public function __construct()
{
parent::__construct();
$this->load->model('user_model'); //load data user model agar bisa di panggil oleh setiap fungsi
}

//List Semua data user
public function index()
{
//Ambil variable semua data user di database dengan memanggil fungsi database
$user = $this->user_model->get_all();
//Tampilkan semua user menggunakan variable $user yang akan di looping
$data = array(
'title' => 'Data User',
'user' => $user,
'content' => 'backend/user/get_user'
);
$this->load->view('backend/layout/wrapp', $data, FALSE);
}
//Create User
public function create()
{
//Fungsi validasi form
$valid = $this->form_validation;
//rules nama harus di isi
$valid->set_rules(
'name',
'Nama',
'required',
array('required' => '%s Tidak boleh kosong')
);
//rules email harus diisi serta harus unik, sehingga tidak terjadi double email
$valid->set_rules(
'email',
'Email',
'required|valid_email|trim|is_unique[user.email]',
array(
'required' => '%s Tidak boleh kosong',
'is_unique' => '%s <strong>' . $this->input->post('email') .
'</strong> sudah digunakan. Silahkan gunakan email yang lain!',
'valid_email' => 'Format %s Tidak Valid'
)
);
//Rules Role
$valid->set_rules(
'role',
'Role',
'required',
array('required' => 'Silahkan pilih %s ')
);
//Rules status
$valid->set_rules(
'status',
'Status',
'required',
array('required' => 'Silahkan pilih %s ')
);
//Rules password harus di isi
$valid->set_rules(
'password',
'Password',
'required',
array('required' => '%s Tidak boleh kosong')
);
if ($valid->run()) {
$config['upload_path'] = './assets/uploads/avatars/';
//Foto Avatar akan disimpan di folder assets/uploads/avatars
//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('avatar')) {

//Jika Validasi Gagal tampilkan error disini
$data = array(
'title' => 'Tambah User',
'error_upload' => $this->upload->display_errors(),
'content' => 'backend/user/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 user
$data = array(
'name' => $this->input->post('name'),
'avatar' => $upload_data['uploads']['file_name'],
'email' => $this->input->post('email'),
'password' => sha1($this->input->post('password')),
'role' => $this->input->post('role'),
'status' => $this->input->post('status'),
'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->user_model->create($data);
//Jika berhasil tampilkan pesan berhasil
$this->session->set_flashdata('sukses', 'Data telah ditambahkan');
//Lalu redirect ke halaman list User
redirect(base_url('admin/user'), 'refresh');
}
}
//Proses pengiriman ke database selesai
//Menampilkan halaman create user
$data = array(
'title' => 'Tambah User',
'content' => 'backend/user/create'
);
$this->load->view('backend/layout/wrapp', $data, FALSE);
}
//Fungsi untuk mengubah data profile user
public function update($id)
{
//Ambil id user yang akan di ubah
$user = $this->user_model->detail($id);
//Validasi form
$valid = $this->form_validation;

$valid->set_rules(
'name',
'Nama',
'required',
array('required' => '%s harus diisi')
);

$valid->set_rules(
'email',
'Email',
'required|valid_email',
array(
'required' => '%s harus diisi',
'valid_email' => 'Format %s Tidak Valid'
)
);


if ($valid->run()) {

//Jika Foto Avatar tidak di ganti
if (!empty($_FILES['avatar']['name'])) {

$config['upload_path'] = './assets/uploads/avatars/';
//Foto Avatar akan disimpan di folder assets/uploads/avatars
//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('avatar')) {

//Jika validasi gagal tampilkan data berdasarkan id user yang di pilih
$data = array(
'title' => 'Update User: ' . $user->nama,
'user' => $user,
'error_upload' => $this->upload->display_errors(),
'content' => 'backend/user/update'
);
$this->load->view('backend/layout/wrapp', $data, FALSE);
} else {

//Jika validasi berhasil maka
$upload_data = array('uploads' => $this->upload->data());
//Foto Avatar akan disimpan di folder assets/uploads/avatars
//Pastikan kamu sudah membuat folder di atas

// Hapus Foto Avatar Lama Jika ada foto baru yang di upload
if ($user->avatar != "") {
unlink('./assets/uploads/avatars/' . $user->avatar);
}
//Proses penghapusan selesai
//lalu ambil data yang dikirim melalui form update user
$data = array(
'id' => $id,
'name' => $this->input->post('name'),
'avatar' => $upload_data['uploads']['file_name'],
'email' => $this->input->post('email'),
'role' => $this->input->post('role'),
'status' => $this->input->post('status'),
'updated_at' => date('Y-m-d H:i:s')
);
//Proses Update data ke database
$this->user_model->update($data);
//Jika berhasil tampilkan pesan
$this->session->set_flashdata('message', 'Data User <b>' . $user->name . '</b> telah di Update');
redirect(base_url('admin/user'), 'refresh');
}
} else {
//Jika Update data user tanpa mengupload Foto Avatar
$i = $this->input;
// Hapus Gambar Lama Jika ada upload foto baru
if ($user->avatar != "")
$data = array(
'id' => $id,
'name' => $this->input->post('name'),
'email' => $this->input->post('email'),
'role' => $this->input->post('role'),
'status' => $this->input->post('status'),
'updated_at' => date('Y-m-d H:i:s')
);
$this->user_model->update($data);
$this->session->set_flashdata('message', 'Data User <b> ' . $user->name . ' </b>telah diubah');
redirect(base_url('admin/user'), 'refresh');
}
}
//Proses Masuk database Selesai
$data = array(
'title' => 'Update User ' . $user->name,
'user' => $user,
'content' => 'backend/user/update'
);
$this->load->view('backend/layout/wrapp', $data, FALSE);
}
//Fungsi hapus data user
public function delete($id)
{
$this->cek_login->cek();
//dapatkan id user yang akan di hapus
$user = $this->user_model->detail($id);
//Hapus foto Avatar
if ($user->avatar != "") {
unlink('./assets/uploads/avatars/' . $user->avatar);
}
//kirim data user yang akan di hapus berdasarkan id user
$data = array('id' => $user->id);
//menjalankan perintah penghapusan user
$this->user_model->delete($data);
//jika berhasil tampilkan pesan bahwa data user telah di hapus
$this->session->set_flashdata('message', 'Data User <b> ' . $user->name . '</b> telah di Hapus');
redirect(base_url('admin/user'), 'refresh');
}
}

Kita akan menyimpan foto avatar maka kita harus siapkan folder tempat menyimpan foto avatar setelah di upload silahkan buat folder uploads di direktory assets. lalu di dalam folder uploads buat satu folder lagi beri nama avatars.

Oke sekarang kita buat sebuah model, silahkan buka direktory application/models lalu buat file dengan nama User_model.php, kemudian copy data berikut ini :

<?php
defined('BASEPATH') or exit('No direct script access allowed');

class User_model extends CI_Model
{
//load database
public function __construct()
{
parent::__construct();
$this->load->database();
}
//Ambil semua data user
public function get_all()
{
$this->db->select('*');
$this->db->from('user');
$this->db->order_by('id', 'DESC');
$query = $this->db->get();
return $query->result();
}
//Detail data user berdasarkan id
public function detail($id)
{
$this->db->select('*');
$this->db->from('user');
$this->db->where('id', $id);
$query = $this->db->get();
return $query->row();
}
//Login user
public function login($email, $password)
{
$this->db->select('*');
$this->db->from('user');
$this->db->where(array(
'email' => $email,
'password' => sha1($password),
'status' => 1
));
$query = $this->db->get();
return $query->row();
}
//Menambahkan data
public function create($data)
{
$this->db->insert('user', $data);
}
//Mengubah data
public function update($data)
{
$this->db->where('id', $data['id']);
$this->db->update('user', $data);
}
//Menghapus Data
public function delete($data)
{
$this->db->where('id', $data['id']);
$this->db->delete('user', $data);
}
}

Nah sekarang kita akan membuat konten view untuk menampilkan data user. Sekarang buka file get_user.php yang ada di direktory application/views/backend/user lalu ganti semua kode dengan kode 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/user/create'); ?>" class="btn btn-primary btn-icon-split">
<span class="icon text-white-50">
<i class="fas fa-user-plus"></i>
</span>
<span class="text">Tambah User</span>
</a>
</div>
<?php
if ($this->session->flashdata('message')) {
echo '<div class="alert alert-success">';
echo $this->session->flashdata('message');
echo '</div>';
}
echo validation_errors('<div class="alert alert-warning">', '</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>Nama</th>
<th>Email</th>
<th>Role</th>
<th>Status</th>
<th width="20%">Aksi</th>
</tr>
</thead>
<tbody>
<?php $i = 1;
foreach ($user as $user) { ?>
<tr>
<td><?php echo $i; ?></td>
<td><?php echo $user->name; ?></td>
<td><?php echo $user->email; ?></td>
<td><?php echo $user->role; ?></td>
<td>
<?php if ($user->status == 1) { ?>
<span class="badge badge-info p-2">Aktif</span>
<?php } else {; ?>
<span class="badge badge-secondary p-2">Nonactive</span>
<?php }; ?>
</td>
<td>
<a href="<?php echo base_url('admin/user/update/' . $user->id); ?> " class="btn btn-success btn-sm"><i class="fas fa-user-edit"></i> Edit</a>
<?php include "delete.php"; ?>
</td>
</tr>
<?php $i++;
} ?>
</tbody>
</table>
</div>
</div>
</div>

Sekarang kita buat halaman untuk membuat user baru silahkan buat file dengan nama create.php di folder views/backend/user kemudian tambahkan kode php seperti di bawah ini :

<div class="col-md-8">
<div class="card shadow mb-4">
<div class="card-header">
Create New User
</div>
<div class="card-body">

<?php
// Form Open
echo form_open_multipart(base_url('admin/user/create'));
?>

<div class="row">
<div class="col-md-3">
<label>Nama <span class="text-danger">*</span></label>
</div>
<div class="col-md-9">
<div class="form-group">

<input type="text" name="name" class="form-control" placeholder="Nama lengkap" value="<?php echo set_value('name') ?>">
<?php echo form_error('name', '<span class="text-danger">', '</span>'); ?>
</div>
</div>
<div class="col-md-3">
<label>Email <span class="text-danger">*</span></label>
</div>
<div class="col-md-9">
<div class="form-group">
<input type="email" name="email" class="form-control" placeholder="Email" value="<?php echo set_value('email') ?>">
<?php echo form_error('email', '<span class="text-danger">', '</span>'); ?>
</div>
</div>
<div class="col-md-3">
<label>Role <span class="text-danger">*</span></label>
</div>
<div class="col-md-9">
<div class="form-group">
<select name="role" class="form-control">
<option></option>
<option value="Superadmin">Superadmin</option>
<option value="Admin">Admin</option>
<option value="Penulis">Penulis</option>
</select>
<?php echo form_error('role', '<span class="text-danger">', '</span>'); ?>
</div>
</div>
<div class="col-md-3">
<label>Status <span class="text-danger">*</span></label>
</div>
<div class="col-md-9">
<div class="form-group">
<select name="status" class="form-control">
<option></option>
<option value="1">Active</option>
<option value="0">Nonactive</option>
</select>
<?php echo form_error('status', '<span class="text-danger">', '</span>'); ?>
</div>
</div>
<div class="col-md-3">
<label>Password <span class="text-danger">*</span></label>
</div>
<div class="col-md-9">
<div class="form-group">
<input type="password" name="password" class="form-control" placeholder="Password" value="<?php echo set_value('password') ?>">
<?php echo form_error('password', '<span class="text-danger">', '</span>'); ?>
</div>
</div>
<div class="col-md-3">
<label>Upload Foto <span class="text-danger">*</span></label>
</div>
<div class="col-md-9">
<div class="form-group">
<input type="file" name="avatar">
</div>
</div>
<div class="col-md-3">

</div>
<div class="col-md-9">
<div class="form-group">
<button type="submit" name="submit" class="btn btn-primary btn-lg"><i class="fa fa-save"></i> Simpan User</button>
</div>
</div>

</div>

<?php
//form Close
echo form_close();
?>

</div>
</div>
</div>

Nah sekarang kita akan membuat halaman update silahkan buat file dengan nama update.php lalu copy code di bawah ini

<div class="col-md-8">
<div class="card shadow mb-4">
<div class="card-header">
<?php echo $title; ?>
</div>
<div class="card-body">
<?php
// Form Open
echo form_open_multipart(base_url('admin/user/update/' . $user->id));
?>
<div class="row">
<div class="col-md-3">
<label>Nama User</label>
</div>
<div class="col-md-9">
<div class="form-group">
<input type="text" name="name" class="form-control" placeholder="Nama lengkap" value="<?php echo $user->name; ?>">
</div>
</div>
<div class="col-md-3">
<label>Email</label>
</div>
<div class="col-md-9">
<div class="form-group">
<input type="text" name="email" class="form-control" placeholder="Email" value="<?php echo $user->email; ?>" readonly>
</div>
</div>
<div class="col-md-3">
<label>Role</label>
</div>
<div class="col-md-9">
<div class="form-group">
<select name="role" class="form-control">
<option value="Superadmin">Superadmin</option>
<option value="Admin" <?php if ($user->role == "Admin") {
echo "selected";
} ?>>Admin</option>
<option value="Penulis" <?php if ($user->role == "Penulis") {
echo "selected";
} ?>>Penulis</option>
</select>
</div>
</div>
<div class="col-md-3">
<label>Status</label>
</div>
<div class="col-md-9">
<div class="form-group">
<select name="status" class="form-control">
<option value="1">Active</option>
<option value="0" <?php if ($user->status == 0) {
echo "selected";
} ?>>Nonactive</option>
</select>
</div>
</div>
<div class="col-md-3">
<label>Upload Foto</label>
</div>
<div class="col-md-9">
<div class="form-group">
<input type="file" name="avatar"><br>
<img class="img-fluid" src="<?php echo base_url('assets/uploads/avatars/' . $user->avatar); ?>">
</div>
</div>
<div class="col-md-3">
</div>
<div class="col-md-9">
<div class="form-group">
<button type="submit" name="submit" class="btn btn-primary btn-lg"><i class="fa fa-save"></i> Update User</button>
</div>
</div>
</div>
<?php
//form Close
echo form_close();
?>
</div>
</div>
</div>

Terakhir kita akan membuat file delete.php di dalam folder views/backend/user kemudian tambahkan kode php di bawah ini

<button type="button" class="btn btn-danger btn-sm" data-toggle="modal" data-target="#Delete<?php
echo $user->id ?>">
<i class="fa fa-trash-o"></i> Hapus
</button>
<div class="modal modal-danger fade" id="Delete<?php echo $user->id ?>">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<h4 class="modal-title">Menghapus Data</h4>
<button type="button" class="close" data-dismiss="modal" aria-label="Close">
<span aria-hidden="true">&times;</span></button>
</div>
<div class="modal-body">
<p>Apakah Anda Yakin Ingin Menghapus User <b><?php echo $user->name ?></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/user/delete/' . $user->id) ?>" class="btn btn-danger pull-right"><i class="fa fa-trash-o"></i> Ya, Hapus data ini</a>
</div>
</div>
</div>
</div>

Oke sampai disini dulu tutorial kita kami ini nanti akan kita lanjut ke tahap login user. Buat kalian yang ingin terus emngikuti tutorial ini silahkan follow by email aja ya. Jadi nanti kalau ada tutorial lanjutan bisa dapet notifikasi dari edikomputer.com

Related posts

Leave a Reply

Your email address will not be published. Required fields are marked *