Kali ini kita akan membuat CRUD pada Laravel 10, untuk cara penginstalannya bisa disimak di blog.aitc.co.id/cara membuat login dan register dilaravel 10
CRUD merupakan singkatan dari Create, Read, Update & Delete. Create artinya penginputan data ke database, Read berarti membaca data dari database, Update berarti mengubah data yang ada di database dan Delete artinya menghapus data yang ada di database.
Berikut langkah-langkah untuk CRUD di Laravel 10:
1. Membuat Tabel Data CRUD (Migration)
Pada tutorial kali ini saya akan menggunakan tabel yang berisi data mahasiswa. Lokasi file: app/models/mahasiswa.php.
Dengan nama kolom/entity-nya yaitu: nrp, nama, alamat dan id (sebagai primary key nya)
Code:
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
class Mahasiswa extends Model
{
use HasFactory;
protected $table="mahasiswas";
protected $primarykey = "id";
protected $fillable = ["nrp","nama","alamat"];
}
Kemudian masukkan perintah php artisan make:migration create_mahasiswa_table --create=mahasiswa
di terminal untuk membuat migrasi pada database.
Membuat tabel. Lokasi file: database/migration/mahasiswa_table
Code:
<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
return new class extends Migration
{
/**
* Run the migrations.
*
* @return void
*/
public function up()
{
Schema::create('mahasiswas', function (Blueprint $table) {
$table->id();
$table->string('nrp',12);
$table->string('nama',100);
$table->string('alamat',200);
$table->timestamps();
});
}
/**
* Reverse the migrations.
*
* @return void
*/
public function down()
{
Schema::dropIfExists('mahasiswas');
}
};
Kemudian masukkan perintah php artisan migrate
di terminal:
Tampilan database :
2. Membuat Controller Dan Model
Pada langkah ini, kita diharuskan membuat resource controller baru sebagai MahasiswaController. Dengan memberikan perintah php artisan make:controller MahasiswaController --resource --model=Mahasiswa
di terminal. Lokasi file: app > Http > Controllers > MahasiswaController.php.
Didalam controllers ini akan otomatis membuat tujuh method secara default, berikut adalah tujuh method default yang terbuat:
- Index
- Create
- store
- edit
- update
- destroy
Code:
<?php
namespace App\Http\Controllers;
use App\Models\Mahasiswa;
use App\Http\Requests\StoreMahasiswaRequest;
use App\Http\Requests\UpdateMahasiswaRequest;
use Illuminate\Http\Request;
class MahasiswaController extends Controller
{
/**
* Display a listing of the resource.
*
* @return \Illuminate\Http\Response
*/
public function index()
{
$dtmhs=Mahasiswa::all();
return view('data_mhs',compact('dtmhs'),['title'=>'data mahasiswa'])
->with('i', (request()->input('page', 1) - 1) * 5);
}
/**
* Show the form for creating a new resource.
*
* @return \Illuminate\Http\Response
*/
public function create()
{
return view('inputdata',['title'=>'input mahasiswa']);
}
/**
* Store a newly created resource in storage.
*
* @param \App\Http\Requests\StoreMahasiswaRequest $request
* @return \Illuminate\Http\Response
*/
public function store(Request $request)
{
//dd($request->all());
Mahasiswa::create([
'nrp'=> $request->nrp,
'nama'=> $request->nama,
'alamat'=> $request->alamat,
]);
return redirect('/');
}
/**
* Display the specified resource.
*
* @param \App\Models\Mahasiswa $mahasiswa
* @return \Illuminate\Http\Response
*/
public function show(Mahasiswa $mahasiswa)
{
//
}
/**
* Show the form for editing the specified resource.
*
* @param \App\Models\Mahasiswa $mahasiswa
* @return \Illuminate\Http\Response
*/
public function edit($id)
{
$dtmhs=Mahasiswa::findorfail($id);
return view('editdata',compact('dtmhs'),['title'=>'Halaman Edit']);
}
/**
* Update the specified resource in storage.
*
* @param \App\Http\Requests\UpdateMahasiswaRequest $request
* @param \App\Models\Mahasiswa $mahasiswa
* @return \Illuminate\Http\Response
*/
public function update(Request $request, $id)
{
$dtmhs=Mahasiswa::findorfail($id);
$dtmhs->update($request->all());
return redirect('/');
}
/**
* Remove the specified resource from storage.
*
* @param \App\Models\Mahasiswa $mahasiswa
* @return \Illuminate\Http\Response
*/
public function destroy($id)
{
$dtmhs=Mahasiswa::findorfail($id);
$dtmhs->delete();
return back();
}
}
3. Menambahkan Resource Route
Lokasi file: Routes/Web
Code:
<?php
use Illuminate\Support\Facades\Route;
use App\Http\Controllers\MahasiswaController;
/*
|--------------------------------------------------------------------------
| Web Routes
|--------------------------------------------------------------------------
|
| Here is where you can register web routes for your application. These
| routes are loaded by the RouteServiceProvider within a group which
| contains the "web" middleware group. Now create something great!
|
*/
Route::get('/',[MahasiswaController::class,'index'])->name('datamahasiswa');
Route::get('/inputdata',[MahasiswaController::class,'create'])->name('inputdata');
Route::post('/simpandata',[MahasiswaController::class,'store'])->name('simpandata');
Route::get('/edit/{id}',[MahasiswaController::class,'edit'])->name('edit');
Route::post('/updatedata/{id}',[MahasiswaController::class,'update'])->name('updatedata');
Route::get('/hapus/{id}',[MahasiswaController::class,'destroy'])->name('hapus');
4. Menambahkan file blade
pada bagian ini merupakan langkah untuk membuat tampilan website project yang telah dibuat.
Lokasi file : resources/view
Layout.blade.php
<!DOCTYPE html>
<html>
<head>
<title>Laravel 10 CRUD Application - ItSolutionStuff.com</title>
<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.0.2/dist/css/bootstrap.min.css" rel="stylesheet">
</head>
<body>
<div class="container">
@yield('content')
</div>
</body>
</html>
Data_mhs.blade.php
@extends('layout')
@section('content')
<div class="row">
<div class="col-lg-12 margin-tb">
<div class="pull-left">
<h2>Laravel 10 CRUD by aitc</h2>
</div>
<div class="pull-right">
<a class="btn btn-success" href="{{ route('inputdata') }}"> Tambah Mahasiswa Baru</a>
</div>
</div>
</div>
@if ($message = Session::get('success'))
<div class="alert alert-success">
<p>{{ $message }}</p>
</div>
@endif
<table class="table table-bordered">
<tr>
<th>No</th>
<th>Nim</th>
<th>Nama</th>
<th>Alamat</th>
<th width="280px">Action</th>
</tr>
@foreach ($dtmhs as $item)
<tr>
<td>{{ ++$i }}</td>
<td>{{ $item->nrp }}</td>
<td>{{ $item->nama }}</td>
<td>{{ $item->alamat }}</td>
<td>
<form action="{{ route('hapus',$item->id) }}" method="POST">
<a class="btn btn-primary" href="{{ route('edit',$item->id) }}">Edit</a>
<a class="btn btn-danger" href="{{ route('hapus',$item->id) }}">Hapus</a>
</form>
</td>
</tr>
@endforeach
</table>
@endsection
Inputdata.blade.php
@extends('layout')
@section('content')
<div class="row">
<div class="col-lg-12 margin-tb">
<div class="pull-left">
<h2>Tambah Mahasiswa baru</h2>
</div>
<div class="pull-right">
<a class="btn btn-primary" href="{{ route('datamahasiswa') }}"> Kembali</a>
</div>
</div>
</div>
@if ($errors->any())
<div class="alert alert-danger">
<strong>Whoops!</strong> Ada beberapa masalah terkait beberapa data yang anda masukkan.<br><br>
<ul>
@foreach ($errors->all() as $error)
<li>{{ $error }}</li>
@endforeach
</ul>
</div>
@endif
<form action="{{ route('simpandata') }}" method="POST">
@csrf
<div class="row">
<div class="col-xs-12 col-sm-12 col-md-12">
<div class="form-group">
<strong>Nim:</strong>
<input type="text" name="nrp" class="form-control" placeholder="Nim">
</div>
</div>
<div class="col-xs-12 col-sm-12 col-md-12">
<div class="form-group">
<strong>Nama:</strong>
<input type="text" name="nama" class="form-control" placeholder="Nama">
</div>
</div>
<div class="col-xs-12 col-sm-12 col-md-12">
<div class="form-group">
<strong>Alamat:</strong>
<input type="text" name="alamat" class="form-control" placeholder="Alamat">
</div>
</div>
<div class="col-xs-12 col-sm-12 col-md-12 text-center">
<button type="submit" class="btn btn-primary">kirim</button>
</div>
</div>
</form>
@endsection
Editdata.blade.php
@extends('layout')
@section('content')
<div class="row">
<div class="col-lg-12 margin-tb">
<div class="pull-left">
<h2>Edit Data Mahasiswa</h2>
</div>
<div class="pull-right">
<a class="btn btn-primary" href="{{ route('datamahasiswa') }}"> Kembali</a>
</div>
</div>
</div>
@if ($errors->any())
<div class="alert alert-danger">
<strong>Whoops!</strong> Ada beberapa masalah terkait beberapa data yang anda masukkan.<br><br>
<ul>
@foreach ($errors->all() as $error)
<li>{{ $error }}</li>
@endforeach
</ul>
</div>
@endif
<form action="{{ route('updatedata',$dtmhs->id) }}" method="POST">
@csrf
<div class="row">
<div class="col-xs-12 col-sm-12 col-md-12">
<div class="form-group">
<strong>Nim:</strong>
<input type="text" name="nrp" class="form-control" placeholder="Nim" value="{{ $dtmhs->nrp }}" >
</div>
</div>
<div class="col-xs-12 col-sm-12 col-md-12">
<div class="form-group">
<strong>Nama:</strong>
<input type="text" name="nama" class="form-control" placeholder="Nama" value="{{ $dtmhs->nama }}" >
</div>
</div>
<div class="col-xs-12 col-sm-12 col-md-12">
<div class="form-group">
<strong>Alamat:</strong>
<input type="text" name="alamat" class="form-control" placeholder="Alamat" value="{{ $dtmhs->alamat }}" >
</div>
</div>
<div class="col-xs-12 col-sm-12 col-md-12 text-center">
<button type="submit" class="btn btn-primary">kirim</button>
</div>
</div>
</form>
@endsection
5. Tampilan
Home
Tambah data
Berhasil di tambah
Edit data
Berhasil di edit
Berhasil di hapus