In this tutorial, I will show you how to create an AJAX-based CRUD (Create, Read, Update, Delete) application in Laravel 12 using jQuery and Bootstrap. With AJAX, we can perform operations without reloading the page, making our application faster and more user-friendly.
I will cover everything step by step, from setting up Laravel 12 to implementing AJAX requests for CRUD operations. By the end of this guide, you will have a fully functional AJAX-powered CRUD system.
Step-by-Step Guide to Laravel 12 AJAX CRUD
Run the following command to create a new Laravel project:
laravel new laravel-12-ajax-crud
Configure your database in the .env file:
DB_CONNECTION=mysql
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE=laravel_12_ajax_crud
DB_USERNAME=root
DB_PASSWORD=
Run migrations to create default tables:
php artisan migrate
Generate a model, migration, and controller for the Post entity:
php artisan make:model Post -mcr
Update the Migration File:
Modify the migration file in database/migrations/ to define the table schema:
<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
return new class extends Migration
{
/**
* Run the migrations.
*/
public function up(): void
{
Schema::create('posts', function (Blueprint $table) {
$table->id();
$table->string('title');
$table->text('content');
$table->timestamps();
});
}
/**
* Reverse the migrations.
*/
public function down(): void
{
Schema::dropIfExists('posts');
}
};
Run the migration:
php artisan migrate
Open app/Models/Post.php and update it:
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Factories\HasFactory;
class Post extends Model
{
use HasFactory;
protected $fillable = ['title', 'content'];
}
Open routes/web.php and add these routes:
<?php
use Illuminate\Support\Facades\Route;
use App\Http\Controllers\PostController;
Route::get('/', function () {
return view('posts.index');
});
Route::controller(PostController::class)->group(function () {
Route::get('/posts', 'index');
Route::post('/posts', 'store');
Route::get('/posts/{post}', 'show');
Route::put('/posts/{post}', 'update');
Route::delete('/posts/{post}', 'destroy');
});
Open app/Http/Controllers/PostController.php and update it:
namespace App\Http\Controllers;
use App\Models\Post;
use Illuminate\Http\Request;
class PostController extends Controller
{
public function index()
{
return response()->json(Post::latest()->get());
}
public function store(Request $request)
{
$request->validate([
'title' => 'required',
'content' => 'required',
]);
$post = Post::create($request->all());
return response()->json($post);
}
public function show(Post $post)
{
return response()->json($post);
}
public function update(Request $request, Post $post)
{
$request->validate([
'title' => 'required',
'content' => 'required',
]);
$post->update($request->all());
return response()->json($post);
}
public function destroy(Post $post)
{
$post->delete();
return response()->json(['message' => 'Post deleted successfully']);
}
}
Create a new file resources/views/posts/index.blade.php and add the following code:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Laravel 12 AJAX CRUD</title>
<link href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css" rel="stylesheet">
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
</head>
<body>
<div class="container mt-5">
<h2 class="mb-4">Laravel 12 AJAX CRUD</h2>
<button class="btn btn-primary mb-3" onclick="addPost()">Add Post</button>
<table class="table table-bordered">
<thead>
<tr>
<th>ID</th>
<th>Title</th>
<th>Actions</th>
</tr>
</thead>
<tbody id="postTable"></tbody>
</table>
</div>
<script>
$(document).ready(function() {
fetchPosts();
});
function fetchPosts() {
$.get("/posts", function(posts) {
let rows = "";
posts.forEach(post => {
rows += `
<tr>
<td>${post.id}</td>
<td>${post.title}</td>
<td>
<button class="btn btn-warning btn-sm" onclick="editPost(${post.id})">Edit</button>
<button class="btn btn-danger btn-sm" onclick="deletePost(${post.id})">Delete</button>
</td>
</tr>`;
});
$("#postTable").html(rows);
});
}
function addPost() {
let title = prompt("Enter title:");
let content = prompt("Enter content:");
if (title && content) {
$.post("/posts", { title, content, _token: "{{ csrf_token() }}" }, function() {
fetchPosts();
});
}
}
function editPost(id) {
$.get(`/posts/${id}`, function(post) {
let title = prompt("Edit title:", post.title);
let content = prompt("Edit content:", post.content);
if (title && content) {
$.ajax({
url: `/posts/${id}`,
type: "PUT",
data: { title, content, _token: "{{ csrf_token() }}" },
success: function() {
fetchPosts();
}
});
}
});
}
function deletePost(id) {
if (confirm("Are you sure?")) {
$.ajax({
url: `/posts/${id}`,
type: "DELETE",
data: { _token: "{{ csrf_token() }}" },
success: function() {
fetchPosts();
}
});
}
}
</script>
</body>
</html>
Start the Laravel server:
php artisan serve
You might also like: