In web development, I find it crucial to create applications that provide a smooth and interactive user experience. That's why I often turn to AJAX (Asynchronous JavaScript and XML), a powerful tool that enables me to achieve this goal.
By combining AJAX with Laravel, a popular PHP framework known for its simplicity and efficiency, I can create web applications that deliver seamless and dynamic user interactions without the need for page refreshes.
In this article, I will delve into the world of AJAX CRUD (Create, Read, Update, Delete) operations in Laravel 10. Whether you're an aspiring developer looking to enhance your skills or a seasoned professional seeking to leverage the latest techniques.
This comprehensive guide will equip you with the knowledge and practical know-how to implement AJAX-powered CRUD functionality in your Laravel 10 applications.
By mastering AJAX CRUD operations, I am able to build applications that allow users to add, view, edit, and delete records in a fluid and responsive manner.
Gone are the days of clunky page reloads and data submission delays. With AJAX, I can seamlessly update web pages in real time, providing a more engaging and enjoyable experience for my users.
Throughout this article, I will cover the essential concepts and techniques needed to perform each CRUD operation using AJAX in Laravel 10. From setting up the development environment to writing the necessary code, I will guide you step-by-step through the process, ensuring you gain a comprehensive understanding of how everything fits together.
Whether you're building a simple contact management system or a complex data-driven application, mastering AJAX CRUD operations in Laravel 10 will prove to be an invaluable skill set.
So, let's dive in together and explore the fascinating world of AJAX-powered CRUD operations in Laravel 10, unlocking the potential to create truly dynamic and user-friendly web applications.
If you haven't installed Laravel yet, follow these steps to set up your local development environment and create a project using the following command.
composer create-project --prefer-dist laravel/laravel ajax_crud_laravel_10
Ensure that you have Laravel 10 installed and configured on your local development environment.
DB_CONNECTION=mysql
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE=laravel_10_ajax_crud
DB_USERNAME=root
DB_PASSWORD=
Now, we will create migration for the "products" table using the laravel php artisan command.
php artisan make:migration create_products_table --create=products
Migration:
<?php
use Illuminate\Support\Facades\Schema;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;
class CreateProductsTable extends Migration {
/**
* Run the migrations.
*
* @return void */
public function up()
{
Schema::create('products', function (Blueprint $table) {
$table->bigIncrements('id');
$table->string('title')->nullable();
$table->longText('description')->nullable();
$table->timestamps();
});
}
/**
* Reverse the migrations.
*
* @return void
*/
public function down()
{
Schema::dropIfExists('products');
}
}
After this, we need to run this migration by the following command in our terminal.
php artisan migrate
Open the routes/web.php
file and define the necessary routes for CRUD operations.
routes/web.php
<?php
use Illuminate\Support\Facades\Route;
use App\Http\Controllers\ProductAjaxController;
/*
|--------------------------------------------------------------------------
| Web Routes
|--------------------------------------------------------------------------
|
| Here is where you can register web routes for your application. These
| routes are loaded by the RouteServiceProvider within a group that
| contains the "web" middleware group. Now create something great!
|
*/
Route::resource('products', ProductAjaxController::class);
Now, we will create the ProductAjaxController and Product Model using the following command.
php artisan make:controller ProductAjaxController --resource --model=Product
Now, make changes in the Product Model. So, add the following code to that file.
App/Models/Product.php
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Model;
class Product extends Model
{
protected $fillable = [
'id', 'title', 'description'
];
}
Open the ProductAjaxController.php file and implement the methods for index, store, update, and destroy operations.
app/Http/Controllers/ProductAjaxController.php
<?php
namespace App\Http\Controllers;
use App\Models\Product;
use Illuminate\Http\Request;
use DataTables;
class ProductAjaxController extends Controller
{
/**
* Display a listing of the resource.
*
* @return \Illuminate\Http\Response
*/
public function index(Request $request)
{
if ($request->ajax()) {
$product = Product::latest()->get();
return Datatables::of($data)
->addIndexColumn()
->addColumn('action', function($row){
$btn = '<a href="javascript:void(0)" data-toggle="tooltip" data-id="'.$row->id.'" data-original-title="Edit" class="edit btn btn-primary btn-sm editProduct">Edit</a>';
$btn = $btn.' <a href="javascript:void(0)" data-toggle="tooltip" data-id="'.$row->id.'" data-original-title="Delete" class="btn btn-danger btn-sm deleteProduct">Delete</a>';
return $btn;
})
->rawColumns(['action'])
->make(true);
}
return view('productAjax',compact('product'));
}
/**
* Store a newly created resource in storage.
*
* @param \Illuminate\Http\Request $request
* @return \Illuminate\Http\Response
*/
public function store(Request $request)
{
Product::updateOrCreate([
'id' => $request->id,
'title' => $request->title,
'description' => $request->description
]);
return response()->json(['success'=>'Product saved successfully.']);
}
/**
* Show the form for editing the specified resource.
*
* @param \App\Product
* @return \Illuminate\Http\Response
*/
public function edit($id)
{
$product = Product::find($id);
return response()->json($product);
}
/**
* Remove the specified resource from storage.
*
* @param \App\Product
* @return \Illuminate\Http\Response
*/
public function destroy($id)
{
Product::find($id)->delete();
return response()->json(['success'=>'Product deleted successfully.']);
}
}
Create a view file for displaying the list.
resources/views/productAjax.blade.php
<!DOCTYPE html>
<html>
<head>
<title>AJAX CRUD Operations In Laravel 10: Step-by-Step Guide - Vidvatek</title>
<meta name="csrf-token" content="{{ csrf_token() }}">
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery-validate/1.19.0/jquery.validate.js"></script>
<link href="https://cdn.datatables.net/1.10.19/css/dataTables.bootstrap4.min.css" rel="stylesheet">
<script src="https://cdn.datatables.net/1.10.16/js/jquery.dataTables.min.js"></script>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/js/bootstrap.min.js"></script>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/4.1.3/css/bootstrap.min.css"/>
<link href="https://cdn.datatables.net/1.10.16/css/jquery.dataTables.min.css" rel="stylesheet">
<script src="https://cdn.datatables.net/1.10.19/js/dataTables.bootstrap4.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.js"></script>
</head>
<body>
<div class="container">
<h1>AJAX CRUD Operations In Laravel 10: Step-by-Step Guide - Vidvatek</h1>
<a class="btn btn-info" href="javascript:void(0)" id="createNewProduct"> Add New Product</a>
<table class="table table-bordered data-table">
<thead>
<tr>
<th>No</th>
<th>Title</th>
<th>Description</th>
<th width="280px">Action</th>
</tr>
</thead>
<tbody>
</tbody>
</table>
</div>
<div class="modal fade" id="ajaxModelexa" aria-hidden="true">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<h4 class="modal-title" id="modelHeading"></h4>
</div>
<div class="modal-body">
<form id="productForm" name="productForm" class="form-horizontal">
<input type="hidden" name="id" id="id">
<div class="form-group">
<label for="title" class="col-sm-2 control-label">Title</label>
<div class="col-sm-12">
<input type="text" class="form-control" id="title" name="title" placeholder="Enter Name" value="" required>
</div>
</div>
<div class="form-group">
<label class="col-sm-2 control-label">Description</label>
<div class="col-sm-12">
<textarea id="description" name="description" required placeholder="Enter Description" class="form-control"></textarea>
</div>
</div>
<div class="col-sm-offset-2 col-sm-10">
<button type="submit" class="btn btn-primary" id="savedata" value="create">Save Product</button>
</div>
</form>
</div>
</div>
</div>
</div>
</body>
<script type="text/javascript">
$(function () {
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
var table = $('.data-table').DataTable({
processing: true,
serverSide: true,
ajax: "{{ route('products.index') }}",
columns: [
{data: 'DT_RowIndex', name: 'DT_RowIndex'},
{data: 'title', name: 'title'},
{data: 'description', name: 'description'},
{data: 'action', name: 'action', orderable: false, searchable: false},
]
});
$('#createNewProduct').click(function () {
$('#savedata').val("create-product");
$('#id').val('');
$('#productForm').trigger("reset");
$('#modelHeading').html("Create New Product");
$('#ajaxModelexa').modal('show');
});
$('body').on('click', '.editProduct', function () {
var id = $(this).data('id');
$.get("{{ route('products.index') }}" +'/' + id +'/edit', function (data) {
$('#modelHeading').html("Edit Product");
$('#savedata').val("edit-user");
$('#ajaxModelexa').modal('show');
$('#id').val(data.id);
$('#title').val(data.title);
$('#description').val(data.description);
})
});
$('#savedata').click(function (e) {
e.preventDefault();
$(this).html('Sending..');
$.ajax({
data: $('#productForm').serialize(),
url: "{{ route('products.store') }}",
type: "POST",
dataType: 'json',
success: function (data) {
$('#productForm').trigger("reset");
$('#ajaxModelexa').modal('hide');
table.draw();
},
error: function (data) {
console.log('Error:', data);
$('#savedata').html('Save Changes');
}
});
});
$('body').on('click', '.deleteProduct', function () {
var id = $(this).data("id");
confirm("Are You sure want to delete this Product!");
$.ajax({
type: "DELETE",
url: "{{ route('products.store') }}"+'/'+id,
success: function (data) {
table.draw();
},
error: function (data) {
console.log('Error:', data);
}
});
});
});
</script>
</html>
Now, run the below command in your terminal to get the output.
php artisan serve
That's it! You now have a complete example of performing AJAX CRUD operations in Laravel 10.