In this guide, we will explore how to implement Laravel 11 CRUD operation using Ajax. CRUD, which stands for Create, Read, Update, and Delete, is a fundamental part of most web applications. By integrating Ajax into our CRUD operations, we can make our app faster and more interactive without requiring full-page reloads.
Table of Contents
- Introduction to Laravel 11 and Ajax
- Setting Up Laravel 11 Project
- Creating the Database and Models
- Creating the Controller for CRUD Operations
- Integrating Ajax with CRUD Operations
- Handling Validation and Error Messages
- Routes for CRUD Operations
- Enhancing User Experience with Ajax
- Conclusion
- FAQs : Laravel 11 CRUD Operation using AJAX
Introduction to Laravel 11 and Ajax

Laravel 11 is the latest version of one of the most popular PHP frameworks for web development. It continues to offer powerful tools, clean architecture, and flexibility for building modern web applications. Ajax (Asynchronous JavaScript and XML) is a technology that allows us to send and receive data from the server without reloading the page.
In this post, we’ll walk through how to implement a Laravel 11 CRUD operation using Ajax to make your app more dynamic and user-friendly.
Setting Up Laravel 11 Project
Before we dive into CRUD operations, we need to set up a new Laravel 11 project. You can easily install Laravel 11 using Composer by running the following command:
composer create-project --prefer-dist laravel/laravel laravel11_crud_ajax
After the installation, navigate to your project directory:
cd laravel11_crud_ajax
Next, set up your environment variables (like database connection) in the .env file.
Creating the Database and Models
Once your project is set up, the next step is to create a database. Update the .env file with your database credentials:
DB_DATABASE=your_database
DB_USERNAME=your_username
DB_PASSWORD=your_password
After configuring the database, run the migration to create a table:
php artisan make:model Item -m
In the generated migration file, define the structure for the items table:
Schema::create('items', function (Blueprint $table) {
$table->id();
$table->string('name');
$table->text('description');
$table->timestamps();
});
Run the migration:
php artisan migrate
This creates the items table, where our Laravel 11 CRUD operation using Ajax will take place
Creating the Controller for CRUD Operations
First, let’s create the controller that will handle our CRUD operations. You can create the controller using Artisan by running the following command:
php artisan make:controller ItemController
This will generate the ItemController inside the app/Http/Controllers directory. Inside this controller, we will add methods to handle CRUD operations: index (Read), store (Create), update (Update), and destroy (Delete).
1. Create (Store) Method
The Create operation allows us to add new records to the database. We’ll implement this in the store() method. This method will validate the incoming data, insert the new record, and return a response.
ItemController.php (Create Method)
<?php
namespace App\Http\Controllers;
use App\Models\Item;
use Illuminate\Http\Request;
class ItemController extends Controller
{
// Create (Store) Method
public function store(Request $request)
{
// Validate the request data
$request->validate([
'name' => 'required|string|max:255',
'description' => 'required|string',
]);
// Create a new item
$item = Item::create([
'name' => $request->name,
'description' => $request->description,
]);
// Return a success response
return response()->json([
'message' => 'Item created successfully!',
'item' => $item
], 201);
}
}
2. Read (Index) Method
The Read operation retrieves all the records from the database. In our controller, the index() method will fetch all items and return them as JSON.
ItemController.php (Read Method)
<?php
class ItemController extends Controller
{
// Read (Index) Method
public function index()
{
// Fetch all items
$items = Item::all();
// Return the items as a JSON response
return response()->json([
'items' => $items
]);
}
}
3. Update Method
The Update operation modifies an existing record. In the update() method, we’ll validate the incoming data and update the selected record in the database.
ItemController.php (Update Method)
<?php
class ItemController extends Controller
{
// Update Method
public function update(Request $request, $id)
{
// Validate the request data
$request->validate([
'name' => 'required|string|max:255',
'description' => 'required|string',
]);
// Find the item by its ID
$item = Item::findOrFail($id);
// Update the item with new data
$item->update([
'name' => $request->name,
'description' => $request->description,
]);
// Return a success response
return response()->json([
'message' => 'Item updated successfully!',
'item' => $item
]);
}
}
4. Delete Method
The Delete operation removes a record from the database. In the destroy() method, we’ll delete the record based on its ID.
ItemController.php (Delete Method)
<?php
class ItemController extends Controller
{
// Delete (Destroy) Method
public function destroy($id)
{
// Find the item by its ID and delete it
$item = Item::findOrFail($id);
$item->delete();
// Return a success response
return response()->json([
'message' => 'Item deleted successfully!'
]);
}
}
Integrating Ajax with CRUD Operations
Ajax Request for Creating an Item
Here’s how you can use Ajax to send a POST request to create a new item:
$('#itemForm').submit(function(e) {
e.preventDefault();
let name = $('#name').val();
let description = $('#description').val();
$.ajax({
url: '/items',
method: 'POST',
data: {
_token: $('meta[name="csrf-token"]').attr('content'),
name: name,
description: description
},
success: function(response) {
alert(response.message);
loadItems(); // Reload the items list (optional)
},
error: function(xhr) {
let errors = xhr.responseJSON.errors;
$.each(errors, function(key, value) {
alert(value); // Display validation errors
});
}
});
});
Ajax Request for Reading (Fetching) Items
To dynamically load the items on the page, you can use Ajax to send a GET request to retrieve the data:
function loadItems() {
$.ajax({
url: '/items',
method: 'GET',
success: function(response) {
let itemsTable = $('#itemsTable');
itemsTable.html(''); // Clear the table
$.each(response.items, function(index, item) {
itemsTable.append(`
<tr>
<td>${item.name}</td>
<td>${item.description}</td>
<td>
<button class="edit-btn" data-id="${item.id}">Edit</button>
<button class="delete-btn" data-id="${item.id}">Delete</button>
</td>
</tr>
`);
});
}
});
}
$(document).ready(function() {
loadItems(); // Load items when the page loads
});
Ajax Request for Updating an Item
To update an item using Ajax, you can trigger this when the user clicks an “Edit” button:
$('#itemForm').submit(function(e) {
e.preventDefault();
let itemId = $('#itemId').val(); // Assuming a hidden input for item ID
let name = $('#name').val();
let description = $('#description').val();
$.ajax({
url: `/items/${itemId}`,
method: 'PUT',
data: {
_token: $('meta[name="csrf-token"]').attr('content'),
name: name,
description: description
},
success: function(response) {
alert(response.message);
loadItems(); // Reload the items list
},
error: function(xhr) {
let errors = xhr.responseJSON.errors;
$.each(errors, function(key, value) {
alert(value); // Display validation errors
});
}
});
});
Ajax Request for Deleting an Item
When a user clicks the “Delete” button, you can trigger the delete action via Ajax:
$(document).on('click', '.delete-btn', function() {
let itemId = $(this).data('id');
$.ajax({
url: `/items/${itemId}`,
method: 'DELETE',
data: {
_token: $('meta[name="csrf-token"]').attr('content')
},
success: function(response) {
alert(response.message);
loadItems(); // Reload the items list
}
});
});
Handling Validation and Error Messages
In real-world applications, data validation is crucial. Laravel offers powerful validation out of the box. In the store method of ItemController, you can validate input like this:
$request->validate([
'name' => 'required|string|max:255',
'description' => 'required',
]);
If the validation fails, Laravel will automatically return error messages. You can capture and display them using Ajax.
// Error handling in Ajax
error: function(xhr) {
let errors = xhr.responseJSON.errors;
$.each(errors, function(key, value) {
alert(value); // Display validation errors
});
}
Routes for CRUD Operations
To link the controller methods to their respective routes, you can define the routes in the routes/web.php file.
<?php
use Illuminate\Support\Facades\Route;
use App\Http\Controllers\ItemController;
// Routes for CRUD Operations
Route::get('/items', [ItemController::class, 'index']);
Route::post('/items', [ItemController::class, 'store']);
Route::put('/items/{id}', [ItemController::class, 'update']);
Route::delete('/items/{id}', [ItemController::class, 'destroy']);
Testing the CRUD Operations
Now that we’ve implemented the Laravel 11 CRUD operation using Ajax, it’s time to test it. You can start the Laravel development server by running:
php artisan serve
Open your browser and navigate to the URL provided by Laravel (e.g., http://127.0.0.1:8000/items). Try adding, updating, and deleting items using the Ajax-powered interface.
Enhancing User Experience with Ajax
To further enhance user experience, consider adding loading animations, inline editing, or modal pop-ups. These features, combined with Ajax, can make your CRUD interface more dynamic and user-friendly.
For example, you could implement a loading spinner while Ajax requests are processed:
$.ajax({
beforeSend: function() {
$('#loading').show();
},
complete: function() {
$('#loading').hide();
}
});
Conclusion
In this guide, we’ve covered how to implement a Laravel 11 CRUD operation using Ajax. With Ajax, you can significantly improve your application’s performance by eliminating unnecessary page reloads. By following these steps, you’ll have a fully functional CRUD interface that offers a seamless user experience or for other blog on Laravel click here.
FAQs : Laravel 11 CRUD Operation using AJAX
1. What is CRUD in Laravel?
CRUD stands for Create, Read, Update, and Delete. These are the four basic operations for managing data in a web application.
2. Why use Ajax with CRUD in Laravel?
Using Ajax allows you to perform CRUD operations without refreshing the entire page, leading to a smoother user experience and faster interactions.
3. What are the advantages of Laravel 11?
Laravel 11 offers enhanced performance, new features, and a more refined developer experience compared to previous versions. It’s well-suited for building modern web applications.
Through this Website i came to many more things about programming.
Good work 👏