Untuk membuat fungsi CRUD (Create, Read, Update, Delete) di Laravel dengan metode AJAX, Anda perlu mengikuti langkah-langkah berikut. Di sini, saya akan memberikan contoh untuk entitas sederhana, seperti `Post`.
1. Persiapan Project Laravel
Pastikan anda sudah menginstall laravel terlebih dahulu dan anda juga sudah melakukan konfigurasi database di dalam file .env
2. Buat Model dan Migrasi
Buat model `Post` beserta migrasinya, jalankan perintah di bawah ini di cmd atau terminal
php artisan make:model Post -m
Edit file migrasi di `database/migrations/xxxx_xx_xx_create_posts_table.php`:
Schema::create('posts', function (Blueprint $table) {
$table->id();
$table->string('title');
$table->text('content');
$table->timestamps();
});
Jalankan perintah migrasi di bawah ini dengan cmd atau terminal
php artisan migrate
3. Buat Controller
Buat controller untuk `Post` dengan menjalankan perintah di bawah ini.
php artisan make:controller PostController --resource
Edit `PostController.php` untuk menangani permintaan CRUD:
namespace App\Http\Controllers;
use App\Models\Post;
use Illuminate\Http\Request;
class PostController extends Controller
{
public function index()
{
$posts = Post::all();
return response()->json($posts);
}
public function store(Request $request)
{
$post = Post::create($request->all());
return response()->json($post);
}
public function show($id)
{
$post = Post::find($id);
return response()->json($post);
}
public function update(Request $request, $id)
{
$post = Post::find($id);
$post->update($request->all());
return response()->json($post);
}
public function destroy($id)
{
$post = Post::find($id);
$post->delete();
return response()->json('Post deleted successfully');
}
}
4. Buat Route
Tambahkan route di `routes/web.php`:
Route::resource('posts', PostController::class);
5. Buat Halaman HTML dan AJAX
Buat file `resources/views/posts.blade.php`:
<!DOCTYPE html>
<html>
<head>
<title>Laravel AJAX CRUD</title>
<meta name="csrf-token" content="{{ csrf_token() }}">
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/4.3.1/css/bootstrap.min.css" />
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
</head>
<body>
<div class="container">
<h1>Laravel AJAX CRUD</h1>
<button id="createNewPost" class="btn btn-success">Create New Post</button>
<table class="table table-bordered" id="postTable">
<thead>
<tr>
<th>No</th>
<th>Title</th>
<th>Content</th>
<th width="280px">Action</th>
</tr>
</thead>
<tbody>
</tbody>
</table>
</div>
<script type="text/javascript">
$(document).ready(function () {
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
loadPosts();
function loadPosts() {
$.ajax({
url: "{{ route('posts.index') }}",
type: 'GET',
dataType: 'json',
success: function (data) {
var rows = '';
$.each(data, function (key, post) {
rows += '<tr>';
rows += '<td>' + (key + 1) + '</td>';
rows += '<td>' + post.title + '</td>';
rows += '<td>' + post.content + '</td>';
rows += '<td>';
rows += '<button class="btn btn-primary editPost" data-id="' + post.id + '">Edit</button>';
rows += '<button class="btn btn-danger deletePost" data-id="' + post.id + '">Delete</button>';
rows += '</td>';
rows += '</tr>';
});
$('#postTable tbody').html(rows);
}
});
}
$('#createNewPost').click(function () {
$('#postForm').trigger("reset");
$('#postModal').modal('show');
});
$('body').on('click', '.editPost', function () {
var postId = $(this).data('id');
$.get("{{ route('posts.index') }}" + '/' + postId, function (data) {
$('#postModal').modal('show');
$('#postId').val(data.id);
$('#title').val(data.title);
$('#content').val(data.content);
});
});
$('#postForm').submit(function (e) {
e.preventDefault();
var formData = $(this).serialize();
$.ajax({
url: "{{ route('posts.store') }}",
type: 'POST',
data: formData,
success: function (data) {
$('#postForm').trigger("reset");
$('#postModal').modal('hide');
loadPosts();
}
});
});
$('body').on('click', '.deletePost', function () {
var postId = $(this).data('id');
if (confirm("Are you sure you want to delete this post?")) {
$.ajax({
url: "{{ route('posts.index') }}" + '/' + postId,
type: 'DELETE',
success: function (data) {
loadPosts();
}
});
}
});
});
</script>
<!-- Modal -->
<div class="modal fade" id="postModal" tabindex="-1" aria-labelledby="postModalLabel" aria-hidden="true">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title" id="postModalLabel">Post</h5>
<button type="button" class="close" data-dismiss="modal" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
</div>
<div class="modal-body">
<form id="postForm" name="postForm">
<input type="hidden" name="postId" id="postId">
<div class="form-group">
<label for="title" class="col-form-label">Title:</label>
<input type="text" class="form-control" id="title" name="title">
</div>
<div class="form-group">
<label for="content" class="col-form-label">Content:</label>
<textarea class="form-control" id="content" name="content"></textarea>
</div>
</form>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button>
<button type="button" class="btn btn-primary" id="savePost">Save</button>
</div>
</div>
</div>
</div>
</body>
</html>
Tambahkan route untuk menampilkan halaman ini di `routes/web.php`:
Route::get('posts-view', function () {
return view('posts');
});
Dengan demikian, Anda dapat mengakses halaman CRUD dengan AJAX di URL `http://localhost:8000/posts-view`.
6. Testing
Jalankan server dengan perintah php artisen serve dan akses `http://localhost:8000/posts-view`. Anda harus dapat membuat, membaca, mengupdate, dan menghapus entri `Post` menggunakan AJAX.
Itulah cara dasar untuk membuat fungsi CRUD di Laravel dengan metode AJAX. Anda bisa mengembangkan lebih lanjut sesuai dengan kebutuhan aplikasi Anda.
Sangat membantu💥💥
ReplyDelete