If you want to create a crud application using ajax and DataTable js in laravel 10 web application. In which crud operations can be done without refreshing and reloading the page using pop up modal, dataTable js and jquery ajax.
So, In this tutorial, you will learn how to create ajax crud with popup modal using dataTable js, bootstrap popup modal, and jQuery in laravel 10 apps with page refresh/reload.
Laravel 10 Ajax CRUD with Popup Modal Example
By using these following steps, you can create an ajax crud application using dataTable js, bootstrap popup modal, and jQuery in laravel 10 without page refresh:
- Step 1 – Download Laravel 10 App
- Step 2 – Database Configuration
- Step 3 – Installing Yajra Datatables
- Step 4 – Make Model & Migration
- Step 5 – Make Routes
- Step 6 – Create AJAX CRUD Datatables Controller
- Step 7 – Create Blade Views File
- companies.blade.php
- company-action.blade.php
- Step 8 – Run Development Server
Step 1 – Download Laravel 10 App
Firstly, start your terminal OR command line to download or install Laravel 10 new setup. Execute the following command into it to install new Laravel 10 app into your system:
composer create-project --prefer-dist laravel/laravel LaravelAJAXCRUDDataTable
Step 2 – Database Configuration
Configure the database with your laravel apps. So, visit your app root directory and find & open .env file. Then configure database details as follows:
DB_CONNECTION=mysql
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE=database-name
DB_USERNAME=database-user-name
DB_PASSWORD=database-password
Step 3 – Installing Yajra Datatables
Execute the following command on the terminal or command prompt to install Yajra Datatables Packages in your Laravel 10 apps:
composer require yajra/laravel-datatables-oracle
Then configure DataTables package. So go to the config directory and open app.php file. And add the following service providers into app.php file:
config/app.php
'providers' => [
Yajra\Datatables\DatatablesServiceProvider::class,
],
'aliases' => [
'Datatables' => Yajra\Datatables\Facades\Datatables::class,
]
Then publish Laravel dataTables vendor package by using the following command:
php artisan vendor:publish
Step 4 – Make Model & Migration
Open again your command prompt or terminal. Then execute the following command into it to create model and migration file:
php artisan make:model Company -m
After that, open create_companies_table.php file inside /database/migrations/ directory. And then update the function up() with the following code:
public function up()
{
Schema::create('companies', function (Blueprint $table) {
$table->id();
$table->string('name');
$table->string('email');
$table->string('address');
$table->timestamps();
});
}
Then, open again command prompt or terminal and execute the following command into it to create tables in database:
php artisan migrate
After that, visit app/models directory and open company.php model file. Then add the following code into it:
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
class Company extends Model
{
use HasFactory;
protected $fillable = [ 'name', 'email', 'address' ];
}
Step 5 – Make Routes
Then create routes for laravel ajax crud app. So, visit routes directory and open web.php file. And then add the following routes into the web.php file:
use App\Http\Controllers\DataTableAjaxCRUDController;
Route::get('ajax-crud-datatable', [DataTableAjaxCRUDController::class, 'index']);
Route::post('store-company', [DataTableAjaxCRUDController::class, 'store']);
Route::post('edit-company', [DataTableAjaxCRUDController::class, 'edit']);
Route::post('delete-company', [DataTableAjaxCRUDController::class, 'destroy']);
Step 6 – Create AJAX CRUD Datatables Controller
Create a controller by executing the following command on the command prompt or terminal to create a controller file:
php artisan make:controller DataTableAjaxCRUDController
After that, visit app/Http/controllers directory and open the DataTableAjaxCRUDController.php file. And then add the following code to it:
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Models\Company;
use Datatables;
class DataTableAjaxCRUDController extends Controller
{
/**
* Display a listing of the resource.
*
* @return \Illuminate\Http\Response
*/
public function index()
{
if(request()->ajax()) {
return datatables()->of(Company::select('*'))
->addColumn('action', 'company-action')
->rawColumns(['action'])
->addIndexColumn()
->make(true);
}
return view('companies');
}
/**
* Store a newly created resource in storage.
*
* @param \Illuminate\Http\Request $request
* @return \Illuminate\Http\Response
*/
public function store(Request $request)
{
$companyId = $request->id;
$company = Company::updateOrCreate(
[
'id' => $companyId
],
[
'name' => $request->name,
'email' => $request->email,
'address' => $request->address
]);
return Response()->json($company);
}
/**
* Show the form for editing the specified resource.
*
* @param \App\company $company
* @return \Illuminate\Http\Response
*/
public function edit(Request $request)
{
$where = array('id' => $request->id);
$company = Company::where($where)->first();
return Response()->json($company);
}
/**
* Remove the specified resource from storage.
*
* @param \App\company $company
* @return \Illuminate\Http\Response
*/
public function destroy(Request $request)
{
$company = Company::where('id',$request->id)->delete();
return Response()->json($company);
}
}
Step 6 – Create Blade Views File
Create two blade views file, which are following:
- companies.blade.php
- company-action.blade.php
Go to resources/views directory. And create companies.blade.php and company-action.blade.php. And update the following code into the following this files:
companies.blade.php:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Laravel 10 AJAX CRUD using DataTable js Tutorial From Scratch - Tutsmake.com</title>
<meta name="csrf-token" content="{{ csrf_token() }}">
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.css" >
<script src="https://code.jquery.com/jquery-3.5.1.min.js"></script>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.5.2/js/bootstrap.min.js"></script>
<link href="https://cdn.datatables.net/1.10.21/css/jquery.dataTables.min.css" rel="stylesheet">
<script src="https://cdn.datatables.net/1.10.21/js/jquery.dataTables.min.js"></script>
</head>
<body>
<div class="container mt-2">
<div class="row">
<div class="col-lg-12 margin-tb">
<div class="pull-left">
<h2>Laravel 10 Ajax CRUD DataTables Tutorial</h2>
</div>
<div class="pull-right mb-2">
<a class="btn btn-success" onClick="add()" href="javascript:void(0)"> Create Company</a>
</div>
</div>
</div>
@if ($message = Session::get('success'))
<div class="alert alert-success">
<p>{{ $message }}</p>
</div>
@endif
<div class="card-body">
<table class="table table-bordered" id="ajax-crud-datatable">
<thead>
<tr>
<th>Id</th>
<th>Name</th>
<th>Email</th>
<th>Address</th>
<th>Created at</th>
<th>Action</th>
</tr>
</thead>
</table>
</div>
</div>
<!-- boostrap company model -->
<div class="modal fade" id="company-modal" aria-hidden="true">
<div class="modal-dialog modal-lg">
<div class="modal-content">
<div class="modal-header">
<h4 class="modal-title" id="CompanyModal"></h4>
</div>
<div class="modal-body">
<form action="javascript:void(0)" id="CompanyForm" name="CompanyForm" class="form-horizontal" method="POST" enctype="multipart/form-data">
<input type="hidden" name="id" id="id">
<div class="form-group">
<label for="name" class="col-sm-2 control-label">Company Name</label>
<div class="col-sm-12">
<input type="text" class="form-control" id="name" name="name" placeholder="Enter Company Name" maxlength="50" required="">
</div>
</div>
<div class="form-group">
<label for="name" class="col-sm-2 control-label">Company Email</label>
<div class="col-sm-12">
<input type="email" class="form-control" id="email" name="email" placeholder="Enter Company Email" maxlength="50" required="">
</div>
</div>
<div class="form-group">
<label class="col-sm-2 control-label">Company Address</label>
<div class="col-sm-12">
<input type="text" class="form-control" id="address" name="address" placeholder="Enter Company Address" required="">
</div>
</div>
<div class="col-sm-offset-2 col-sm-10">
<button type="submit" class="btn btn-primary" id="btn-save">Save changes
</button>
</div>
</form>
</div>
<div class="modal-footer">
</div>
</div>
</div>
</div>
<!-- end bootstrap model -->
</body>
<script type="text/javascript">
$(document).ready( function () {
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
$('#ajax-crud-datatable').DataTable({
processing: true,
serverSide: true,
ajax: "{{ url('ajax-crud-datatable') }}",
columns: [
{ data: 'id', name: 'id' },
{ data: 'name', name: 'name' },
{ data: 'email', name: 'email' },
{ data: 'address', name: 'address' },
{ data: 'created_at', name: 'created_at' },
{data: 'action', name: 'action', orderable: false},
],
order: [[0, 'desc']]
});
});
function add(){
$('#CompanyForm').trigger("reset");
$('#CompanyModal').html("Add Company");
$('#company-modal').modal('show');
$('#id').val('');
}
function editFunc(id){
$.ajax({
type:"POST",
url: "{{ url('edit-company') }}",
data: { id: id },
dataType: 'json',
success: function(res){
$('#CompanyModal').html("Edit Company");
$('#company-modal').modal('show');
$('#id').val(res.id);
$('#name').val(res.name);
$('#address').val(res.address);
$('#email').val(res.email);
}
});
}
function deleteFunc(id){
if (confirm("Delete Record?") == true) {
var id = id;
// ajax
$.ajax({
type:"POST",
url: "{{ url('delete-company') }}",
data: { id: id },
dataType: 'json',
success: function(res){
var oTable = $('#ajax-crud-datatable').dataTable();
oTable.fnDraw(false);
}
});
}
}
$('#CompanyForm').submit(function(e) {
e.preventDefault();
var formData = new FormData(this);
$.ajax({
type:'POST',
url: "{{ url('store-company')}}",
data: formData,
cache:false,
contentType: false,
processData: false,
success: (data) => {
$("#company-modal").modal('hide');
var oTable = $('#ajax-crud-datatable').dataTable();
oTable.fnDraw(false);
$("#btn-save").html('Submit');
$("#btn-save"). attr("disabled", false);
},
error: function(data){
console.log(data);
}
});
});
</script>
</html>
Explanation of above-given jQuery, ajax, and javascript code:
On the companies.blade.php, we have created 5 jQuery, ajax, and javascript custom and built-in yajra data tables functions, which are the followings:
- add()
The add() function will contain the given code and it’s show company add modal:
function add(){
$('#CompanyForm').trigger("reset");
$('#CompanyModal').html("Add Company");
$('#company-modal').modal('show');
$('#id').val('');
}
- editFunc()
The editFunc() function will contain the given code and it’s show company edit modal with company details:
function editFunc(id){
$.ajax({
type:"POST",
url: "{{ url('edit-company') }}",
data: { id: id },
dataType: 'json',
success: function(res){
$('#CompanyModal').html("Edit Company");
$('#company-modal').modal('show');
$('#id').val(res.id);
$('#name').val(res.name);
$('#address').val(res.address);
$('#email').val(res.email);
}
});
}
- deleteFunc()
The add() function will contain below given code and it’s delete company from database and yajra datatables:
function deleteFunc(id){
if (confirm("Delete Record?") == true) {
var id = id;
// ajax
$.ajax({
type:"POST",
url: "{{ url('delete-company') }}",
data: { id: id },
dataType: 'json',
success: function(res){
var oTable = $('#ajax-crud-datatable').dataTable();
oTable.fnDraw(false);
}
});
}
}
- DataTable()
The DataTable() function will contain below given code and it’s render list of companies with pagination, search, sorting functionality:
$('#ajax-crud-datatable').DataTable({
processing: true,
serverSide: true,
ajax: "{{ url('ajax-crud-datatable') }}",
columns: [
{ data: 'id', name: 'id' },
{ data: 'name', name: 'name' },
{ data: 'email', name: 'email' },
{ data: 'address', name: 'address' },
{ data: 'created_at', name: 'created_at' },
{data: 'action', name: 'action', orderable: false},
],
order: [[0, 'desc']]
});
- jQuery submit()
This submit function will send data to controller file using ajax for insert or update form data into database:
$('#CompanyForm').submit(function(e) {
e.preventDefault();
var formData = new FormData(this);
$.ajax({
type:'POST',
url: "{{ url('store-company')}}",
data: formData,
cache:false,
contentType: false,
processData: false,
success: (data) => {
$("#company-modal").modal('hide');
var oTable = $('#ajax-crud-datatable').dataTable();
oTable.fnDraw(false);
$("#btn-save").html('Submit');
$("#btn-save"). attr("disabled", false);
},
error: function(data){
console.log(data);
}
});
});
company-action.blade.php
<a href="javascript:void(0)" data-toggle="tooltip" onClick="editFunc({{ $id }})" data-original-title="Edit" class="edit btn btn-success edit">
Edit
</a>
<a href="javascript:void(0);" id="delete-compnay" onClick="deleteFunc({{ $id }})" data-toggle="tooltip" data-original-title="Delete" class="delete btn btn-danger">
Delete
</a>
Don’t forget to add the following yajra Datatables, jquery, and bootstrap library on companies.blade.php file:
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.css" >
<script src="https://code.jquery.com/jquery-3.5.1.min.js"></script>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.5.2/js/bootstrap.min.js"></script>
<link href="https://cdn.datatables.net/1.10.21/css/jquery.dataTables.min.css" rel="stylesheet">
<script src="https://cdn.datatables.net/1.10.21/js/jquery.dataTables.min.js"></script>
Step 8 – Run Development Server
The last step, open the command prompt or terminal and then execute the following command into it to start development server:
php artisan serve
Then open your browser and hit the following URL on it:
http://127.0.0.1:8000/ajax-crud-datatable
Recommended Laravel Posts