Laravel 11 AJAX CRUD means creating, updating, reading, deleting records in the database without refreshing the web page.
To implement Laravel 11 AJAX CRUD operations involves creating a CRUD controller, model, view and using jQuery DataTables.js with Bootstrap popup modal for better UI presentation.
Let’s start implementing AJAX CRUD operations with popup modal:
Step 1: Set up Laravel Application
First, create a new Laravel project using Composer command:
composer create-project --prefer-dist laravel/laravel laravel-ajax-crud
Navigate to your project folder using cd command:
cd laravel-ajax-crud
Step 2: Configure Database
Configure your database credentials in the .env
file.
Step 3: Create Migration and Model
Create a migration and model files to perform create operation through these:
php artisan make:model Product -m
Edit create_products_table.php
migration file from (database/migrations/
folder and define the schema for your products
table like the following:
Schema::create('products', function (Blueprint $table) {
$table->id();
$table->string('name');
$table->text('price')->nullable();
$table->timestamps();
});
Run the migration to create the table in the database:
php artisan migrate
Step 4: Set up CRUD Routes
Define routes in routes/web.php
for handle AJAX CRUD operations requests in laravel 11:
use App\Http\Controllers\ProductController;
Route::resource('products', ProductController::class);
Step 5: Set up Yajra DataTable
Run the following composer command to install and set up dataTable:
composer require yajra/laravel-datatables-oracle
Step 6: Create Controller
Create a controller file for handling AJAX CRUD operations using artisan command:
php artisan make:controller ProductController --resource
Edit your ProductController.php
from app/http/controllers folder, and implement methods to handle AJAX requests for perform CRUD operations with database like the following:
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Models\Product;
use DataTables;
class ProductController extends Controller
{
/**
* Display a listing of the resource.
*
* @return \Illuminate\Http\Response
*/
public function index(Request $request)
{
if ($request->ajax()) {
$data = Product::latest()->get();
return DataTables::of($data)
->addColumn('action', function($row){
$btn = '<button class="btn btn-primary btn-sm editProduct" data-id="' . $row->id . '">Edit</button> ';
$btn .= '<button class="btn btn-danger btn-sm deleteProduct" data-id="' . $row->id . '">Delete</button>';
return $btn;
})
->rawColumns(['action'])
->make(true);
}
return view('index');
}
/**
* Store a newly created resource in storage.
*
* @param \Illuminate\Http\Request $request
* @return \Illuminate\Http\Response
*/
public function store(Request $request)
{
$request->validate([
'name' => 'required',
'price' => 'required|numeric',
// Add validation rules for other fields
]);
Product::create($request->all());
return response()->json(['success' => 'Product created successfully']);
}
/**
* Update the specified resource in storage.
*
* @param \Illuminate\Http\Request $request
* @param \App\Models\Product $product
* @return \Illuminate\Http\Response
*/
public function update(Request $request, Product $product)
{
$request->validate([
'name' => 'required',
'price' => 'required|numeric',
// Add validation rules for other fields
]);
$product->update($request->all());
return response()->json(['success' => 'Product updated successfully']);
}
/**
* Remove the specified resource from storage.
*
* @param \App\Models\Product $product
* @return \Illuminate\Http\Response
*/
public function destroy(Product $product)
{
$product->delete();
return response()->json(['success' => 'Product deleted successfully']);
}
}
Step 7: Create Views
Create views in resources/views folder for displaying the AJAX CRUD interface.
Create index.blade.php
in resources/views folder for listing products and add, edit, delete button with popup modal:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Laravel 11 AJAX CRUD with POPUP Modal Tutorial - ITCODSTUFF.COM</title>
<link href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-QWTKZyjpPEjISv5WaRU9OFeRpok6YctnYmDr5pNlyT2bRjXh0JMhjY6hW+ALEwIH" crossorigin="anonymous">
</head>
<body>
<div class="container mt-2">
<div class="row">
<div class="col-lg-12 margin-tb">
<div class="pull-left">
<h2>Laravel 11 AJAX CRUD with POPUP Modal Tutorial - ITCODSTUFF.COM</h2>
</div>
<div class="pull-right mb-2">
<a class="btn btn-success" href="javascript:void(0)" id="createNewProduct"> Create Product</a>
</div>
</div>
</div>
<div class="container">
<h2>Products List - ITCODSTUFF.COM</h2>
<table class="table" id="product-table">
<thead>
<tr>
<th>ID</th>
<th>Name</th>
<th>Price</th>
<th>Action</th>
</tr>
</thead>
</table>
</div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
<!-- DataTables CSS -->
<link rel="stylesheet" type="text/css" href="https://cdn.datatables.net/1.11.5/css/jquery.dataTables.min.css">
<script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/js/bootstrap.bundle.min.js"></script>
<!-- DataTables JS -->
<script src="https://cdn.datatables.net/1.11.5/js/jquery.dataTables.min.js"></script>
<script>
$(document).ready(function() {
$('#product-table').DataTable({
processing: true,
serverSide: true,
ajax: "{{ route('products.index') }}",
columns: [
{ data: 'id', name: 'id' },
{ data: 'name', name: 'name' },
{ data: 'price', name: 'price' },
{ data: 'action', name: 'action', orderable: false, searchable: false },
]
});
});
</script>
</body>
</html>
Step 8: Display Modals for CRUD Operations
Implement popup modals in index.blade.php
blade file using Bootstrap for creating, updating, and deleting records.
<!-- Create Modal -->
<div class="modal fade" id="ajaxProductModal" aria-hidden="true">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<h4 class="modal-title" id="productCrudModal"></h4>
</div>
<div class="modal-body">
<form id="productForm" name="productForm" class="form-horizontal">
<input type="hidden" name="product_id" id="product_id">
<div class="form-group">
<label for="name" class="col-sm-2 control-label">Name</label>
<div class="col-sm-12">
<input type="text" class="form-control" id="name" name="name" placeholder="Enter Name" value="" maxlength="50" required="">
</div>
</div>
<div class="form-group">
<label class="col-sm-2 control-label">Price</label>
<div class="col-sm-12">
<input type="text" class="form-control" id="price" name="price" placeholder="Enter Price" value="" required="">
</div>
</div>
<div class="col-sm-offset-2 col-sm-10">
<button type="submit" class="btn btn-primary" id="btn-save" value="create">Save changes
</button>
</div>
</form>
</div>
<div class="modal-footer"></div>
</div>
</div>
</div>
Step 9: Implement JavaScript for AJAX Requests
Handle AJAX requests using jQuery ajax for CRUD operations and display the modal accordingly like the following:
<script>
$(document).ready(function() {
$('#createNewProduct').click(function () {
$('#btn-save').val("create-product");
$('#product_id').val('');
$('#productForm').trigger("reset");
$('#productCrudModal').html("Add New Product");
$('#ajaxProductModal').modal('show');
});
$('body').on('click', '.editProduct', function () {
var product_id = $(this).data('id');
$.get('products/'+product_id+'/edit', function (data) {
$('#productCrudModal').html("Edit Product");
$('#btn-save').val("edit-product");
$('#ajaxProductModal').modal('show');
$('#product_id').val(data.id);
$('#name').val(data.name);
$('#price').val(data.price);
})
});
$('body').on('click', '.deleteProduct', function () {
var product_id = $(this).data("id");
if(confirm("Are You sure want to delete !")){
$.ajax({
type: "DELETE",
url: "{{ route('products.store') }}"+'/'+product_id,
success: function (data) {
$('#product_id').val('');
$('#productForm').trigger("reset");
$('#ajaxProductModal').modal('hide');
table.draw();
},
error: function (data) {
console.log('Error:', data);
}
});
}
});
});
</script>
Step 10: Test the Application
Run the artisan serve command to start application for testing:
php artisan serve
Open browser with http://127.0.0.1:8000/products
.
You’ve now implemented a complete Laravel 11 CRUD application with AJAX and DataTables.js integration, including popup modals for creating, updating, and deleting records.
To build Laravel 11 Ajax CRUD application, jQuery AJAX, Bootstrap 5, DataTables JS and Laravel Framework have been used; for reference: