In this tutorial you will learn about the Laravel 9 Ajax CRUD Example Tutorial and its application with practical example.
In this Laravel 9 Ajax CRUD Example Tutorial I’ll show you how to create a simple ajax crud application using Datatables in laravel 9. In this example we will learn how to create a simple ajax crud operation application using Datatables in laravel 9. In this article I will share example to implement ajax based CRUD (Create, Read, Update and Delete) operations using datatable js. In this tutorial, we will be using yajra datatable package for listing of records with pagination, sorting and filter (search) feature.
Laravel 9 Ajax CRUD Example Tutorial
In this step by step guide, we will be creating a simple laravel 9 ajax crud application to demonstrate you how to install yajra datatable package and implement ajax based CRUD operations with datatable js. Please follow the instruction given below:
- Install laravel 9
- Configure Database
- Create Migration And Model
- Install Yajra DataTables
- Make Route
- Create Controller
- Create Blade View
- Start Development Server
Install laravel 9
First of all we need to create a fresh laravel project, download and install Laravel 9 using the below command
1 |
composer create-project --prefer-dist laravel/laravel larablog |
Configure Database
Now, lets create a MySQL database and connect it with laravel application. After creating database we need to set database credential in application’s .env file.
.env
1 2 3 4 5 6 |
DB_CONNECTION=mysql DB_HOST=127.0.0.1 DB_PORT=3306 DB_DATABASE=larablog DB_USERNAME=root DB_PASSWORD= |
Create Migration And Model
Now, in this step we will create model and migration file. Please run the following command:
1 |
php artisan make:model Employee -m |
Now go to database/migrations/ and open create_employees_table.php file. Then update the up() method as following:
1 2 3 4 5 6 7 8 9 10 |
public function up() { Schema::create('employees', function (Blueprint $table) { $table->id(); $table->string('name'); $table->string('email'); $table->string('address'); $table->timestamps(); }); } |
Now, run following command to migrate database schema.
1 |
php artisan migrate |
Next, go to app/Models/Employee.php file and add the $fillable property in the Employee model as following.
1 2 3 4 5 6 7 8 9 10 11 12 13 |
<?php namespace App\Models; use Illuminate\Database\Eloquent\Factories\HasFactory; use Illuminate\Database\Eloquent\Model; class Employee extends Model { use HasFactory; protected $fillable = [ 'name', 'email', 'address' ]; } |
Install Yajra DataTables
In this step, we will install Yajra Datatables Package via the composer dependency manager. Use the following command to install Yajra Datatables Package.
1 |
composer require yajra/laravel-datatables-oracle |
After Installing Yajra Datatables package, we need to add service provider and alias in config/app.php file as following.
config/app.php
1 2 3 4 5 6 7 8 9 |
'providers' => [ // Other service providers… Yajra\DataTables\DataTablesServiceProvider::class, ], 'aliases' => [ // Other aliases… 'Datatables' => Yajra\Datatables\Facades\Datatables::class, ], |
Now, we need to publish laravel datatables vendor package by using the following command:
1 |
php artisan vendor:publish |
Make Route
After this, we need to define routes in “routes/web.php” file. Lets open “routes/web.php” file and add the following routes in it.
routes/web.php
1 2 3 4 5 6 |
use App\Http\Controllers\EmployeeAjaxCRUDController; Route::get('employee-dt-ajax-crud', [EmployeeAjaxCRUDController::class, 'index']); Route::post('store-employee', [EmployeeAjaxCRUDController::class, 'store']); Route::post('edit-employee', [EmployeeAjaxCRUDController::class, 'edit']); Route::post('delete-employee', [EmployeeAjaxCRUDController::class, 'destroy']); |
Create Controller
Next, we have to create a controller for laravel ajax crud operations. Lets Create a controller named EmployeeAjaxCRUDController using command given below –
1 |
php artisan make:controller EmployeeAjaxCRUDController |
Open the EmployeeAjaxCRUDController.php file and put the following code in it.
app/Http/Controllers/EmployeeAjaxCRUDController.php
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 |
<?php namespace App\Http\Controllers; use Illuminate\Http\Request; use App\Models\Employee; use Datatables; class EmployeeAjaxCRUDController extends Controller { public function index() { if(request()->ajax()) { return datatables()->of(Employee::select('*')) ->addColumn('action', 'employee_dt_ajax_crud/employee-action') ->rawColumns(['action']) ->addIndexColumn() ->make(true); } return view('employee_dt_ajax_crud/employees'); } public function store(Request $request) { $EmployeeId = $request->id; $employee = Employee::updateOrCreate( [ 'id' => $EmployeeId ], [ 'name' => $request->name, 'email' => $request->email, 'address' => $request->address ]); return Response()->json($employee); } public function edit(Request $request) { $where = array('id' => $request->id); $employee = Employee::where($where)->first(); return Response()->json($employee); } public function destroy(Request $request) { $employee = Employee::where('id',$request->id)->delete(); return Response()->json($employee); } } |
Create Blade View
In this step we will create a directory and create blade view file for CRUD operations in it. Lets create a folder name employee_dt_ajax_crud inside resources/views directory. Next, create following blade view files in it and put the given code in view file.
employees.blade.php
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 |
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Laravel 9 AJAX CRUD using DataTable</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 9 AJAX CRUD using DataTable</h2> </div> <div class="pull-right mb-2"> <a class="btn btn-success" onClick="add()" href="javascript:void(0)"> Add Employee</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 employee model --> <div class="modal fade" id="employee-modal" aria-hidden="true"> <div class="modal-dialog modal-lg"> <div class="modal-content"> <div class="modal-header"> <h4 class="modal-title" id="EmployeeModal"></h4> </div> <div class="modal-body"> <form action="javascript:void(0)" id="EmployeeForm" name="EmployeeForm" 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">Employee Name</label> <div class="col-sm-12"> <input type="text" class="form-control" id="name" name="name" placeholder="Enter Employee Name" maxlength="50" required=""> </div> </div> <div class="form-group"> <label for="name" class="col-sm-2 control-label">Employee Email</label> <div class="col-sm-12"> <input type="email" class="form-control" id="email" name="email" placeholder="Enter Employee Email" maxlength="50" required=""> </div> </div> <div class="form-group"> <label class="col-sm-2 control-label">Employee Address</label> <div class="col-sm-12"> <input type="text" class="form-control" id="address" name="address" placeholder="Enter Employee 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('employee-dt-ajax-crud') }}", 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(){ $('#EmployeeForm').trigger("reset"); $('#EmployeeModal').html("Add Employee"); $('#employee-modal').modal('show'); $('#id').val(''); } function editFunc(id){ $.ajax({ type:"POST", url: "{{ url('edit-employee') }}", data: { id: id }, dataType: 'json', success: function(res){ $('#EmployeeModal').html("Edit Employee"); $('#employee-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-employee') }}", data: { id: id }, dataType: 'json', success: function(res){ var oTable = $('#ajax-crud-datatable').dataTable(); oTable.fnDraw(false); } }); } } $('#EmployeeForm').submit(function(e) { e.preventDefault(); var formData = new FormData(this); $.ajax({ type:'POST', url: "{{ url('store-employee')}}", data: formData, cache:false, contentType: false, processData: false, success: (data) => { $("#employee-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> |
employee-action.blade.php
1 2 3 4 5 6 |
<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-employee" onClick="deleteFunc({{ $id }})" data-toggle="tooltip" data-original-title="Delete" class="delete btn btn-danger"> Delete </a> |
Start Development Server
Now we are ready to run our example so lets start the development server using following artisan command –
1 |
php artisan serve |
Now, open the following URL in browser to see the output –
1 |
http://localhost:8000/employee-dt-ajax-crud |
Output:-