As a web developer in today's fast-paced digital landscape, I understand the significance of providing a seamless user experience. In my journey as a Laravel developer, I often encounter the need to implement CRUD (Create, Read, Update, Delete) operations within my applications while keeping the user interface clean and intuitive.
One effective approach I've found is to incorporate AJAX and utilize popup modals for data manipulation.
In this article, I will take you on a step-by-step journey of building a complete CRUD application in Laravel 10, enhanced with AJAX and popup modals. By harnessing the power of AJAX, we can perform data operations asynchronously, providing real-time updates and eliminating page reloads for a more responsive user experience.
Additionally, we will integrate popup modals to present data entry forms and confirmation dialogs, making interactions with the application effortless and enjoyable for users.
Throughout this tutorial, we will delve into each aspect in detail, starting with the setup of our Laravel project, designing the database structure, creating routes and controllers, and finally, implementing AJAX and popup modals to handle the CRUD operations.
So, let's see laravel 10 AJAX CRUD operations with popup modal, AJAX laravel CRUD with popup modal, laravel 10 AJAX CRUD example, CRUD operation in laravel 10, how to display data in modal popup laravel.
Ensure you have a Laravel 10 project set up and ready for Laravel 10 AJAX CRUD operation with Modal Popup. If you haven't created a Laravel project yet, you can use the following command to create one.
composer create-project laravel/laravel laravel-10-ajax-crud-modal-popup
Open your terminal or command prompt and navigate to your Laravel project's root directory. Then run the following command to install the yajra datatable package. Laravel DataTables can be installed with Composer. More details about this package in Composer can be found here.
composer require yajra/laravel-datatables-oracle:"^10.0"
If you are using most of the DataTables plugins like Buttons & Html, you can alternatively use the all-in-one installer package.
composer require yajra/laravel-datatables:^9.0
This step is optional if you are using Laravel 5.5+
After installation, add the service provider to the config/app.php
file. Open the file and add the following line to the providers
array.
'providers' => [
// ...
Yajra\DataTables\DataTablesServiceProvider::class,
],
To publish the configuration file, run the following command.
php artisan vendor:publish --tag=datatables
Then, Set up your database configuration in the .env
file.
DB_CONNECTION=mysql
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE=laravel_10_ajax_crud
DB_USERNAME=root
DB_PASSWORD=
In this step, we will create migration and model using the following command. So, run the below command.
php artisan make:migration create_products_table --create=products
Migration:
<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
return new class extends Migration
{
/**
* Run the migrations.
*
* @return void
*/
public function up()
{
Schema::create('products', function (Blueprint $table) {
$table->id();
$table->string('name');
$table->text('detail');
$table->timestamps();
});
}
/**
* Reverse the migrations.
*
* @return void
*/
public function down()
{
Schema::dropIfExists('products');
}
};
Now, we will migrate the product table to the database using the following command.
php artisan migrate
Now, open the Product.php file and add the following code to that file.
app/Models/Product.php
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
class Product extends Model
{
use HasFactory;
/**
* Write code on Method
*
* @return response()
*/
protected $fillable = [
'name', 'detail'
];
}
In your Laravel application, define the routes for handling AJAX requests related to CRUD operations. Open the routes/web.php
file and add the following routes.
routes/web.php
<?php
use Illuminate\Support\Facades\Route;
use App\Http\Controllers\AjaxController;
/*
|--------------------------------------------------------------------------
| Web Routes
|--------------------------------------------------------------------------
|
| Here is where you can register web routes for your application. These
| routes are loaded by the RouteServiceProvider within a group which
| contains the "web" middleware group. Now create something great!
|
*/
Route::resource('ajax-crud', AjaxController::class);
Next, we will create AjaxController using the following command.
php artisan make:controller AjaxController --resource
app/Http/Controllers/AjaxController.php
<?php
namespace App\Http\Controllers;
use App\Models\Product;
use Illuminate\Http\Request;
use DataTables;
class AjaxController 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)
->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('ajax');
}
/**
* 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->product_id
'name' => $request->name,
'detail' => $request->detail
]);
return response()->json(['success'=>'Record saved successfully.']);
}
/**
* Show the form for editing the specified resource.
*
* @param \App\Product $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 $product
* @return \Illuminate\Http\Response
*/
public function destroy($id)
{
Product::find($id)->delete();
return response()->json(['success'=>'Record deleted successfully.']);
}
}
In this step, we will create an ajax.blade.php file. So, add the following HTML code to that file.
resources/views/ajax.blade.php
<!DOCTYPE html>
<html>
<head>
<title>Laravel 10 AJAX CRUD Operations With Popup Modal - Vidvatek</title>
<meta name="csrf-token" content="{{ csrf_token() }}">
<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">
<link href="https://cdn.datatables.net/1.10.19/css/dataTables.bootstrap4.min.css" rel="stylesheet">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery-validate/1.19.0/jquery.validate.js"></script>
<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>
<script src="https://cdn.datatables.net/1.10.19/js/dataTables.bootstrap4.min.js"></script>
</head>
<body>
<div class="container">
<h1>Laravel 10 AJAX CRUD Operations With Popup Modal - Vidvatek</h1>
<a class="btn btn-success" href="javascript:void(0)" id="createNewProduct"> Create New Product</a>
<table class="table table-bordered data-table">
<thead>
<tr>
<th>No</th>
<th>Name</th>
<th>Details</th>
<th width="280px">Action</th>
</tr>
</thead>
<tbody>
</tbody>
</table>
</div>
<div class="modal fade" id="ajaxModel" 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="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">Details</label>
<div class="col-sm-12">
<textarea id="detail" name="detail" required="" placeholder="Enter Details" class="form-control"></textarea>
</div>
</div>
<div class="col-sm-offset-2 col-sm-10">
<button type="submit" class="btn btn-primary" id="saveBtn" value="create">Save changes</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('ajax-crud.index') }}",
columns: [
{data: 'DT_RowIndex', name: 'DT_RowIndex'},
{data: 'name', name: 'name'},
{data: 'detail', name: 'detail'},
{data: 'action', name: 'action', orderable: false, searchable: false},
]
});
$('#createNewProduct').click(function () {
$('#saveBtn').val("create-product");
$('#product_id').val('');
$('#productForm').trigger("reset");
$('#modelHeading').html("Create New Product");
$('#ajaxModel').modal('show');
});
$('body').on('click', '.editProduct', function () {
var product_id = $(this).data('id');
$.get("{{ route('ajax-crud.index') }}" +'/' + product_id +'/edit', function (data) {
$('#modelHeading').html("Edit Product");
$('#saveBtn').val("edit-user");
$('#ajaxModel').modal('show');
$('#product_id').val(data.id);
$('#name').val(data.name);
$('#detail').val(data.detail);
})
});
$('#saveBtn').click(function (e) {
e.preventDefault();
$(this).html('Sending..');
$.ajax({
data: $('#productForm').serialize(),
url: "{{ route('ajax-crud.store') }}",
type: "POST",
dataType: 'json',
success: function (data) {
$('#productForm').trigger("reset");
$('#ajaxModel').modal('hide');
table.draw();
},
error: function (data) {
console.log('Error:', data);
$('#saveBtn').html('Save Changes');
}
});
});
$('body').on('click', '.deleteProduct', function () {
var product_id = $(this).data("id");
confirm("Are You sure want to delete !");
$.ajax({
type: "DELETE",
url: "{{ route('ajax-crud.store') }}"+'/'+product_id,
success: function (data) {
table.draw();
},
error: function (data) {
console.log('Error:', data);
}
});
});
});
</script>
</html>
Now, we will run the laravel 10 AJAX CRUD operation with a model popup using the following command.
php artisan serve
You might also like:
- Read Also: Top 10 Tricks and Tips of Laravel
- Read Also: How to Get Current Date and Time in Python
- Read Also: Step-by-Step Guide: Installing React.js on Ubuntu
- Read Also: AJAX CRUD Operations In Laravel 10: Step-by-Step Guide