Laravel 8 CRUD Operation With Ajax Example

In this post we will learn how to Laravel 8 CRUD Operation With Ajax Example. 

Also we learn laravel 8 Ajax CRUD Tutorial with Example, Laravel 8  Ajax CRUD With yajra Datatable, Laravel 8 Ajax CRUD Tutorial Using Datatable ect.

Laravel 8 CRUD Operation With Ajax Example

Install Yajra Datatable Package

We need to install yajra datatable composer package for datatable, so you can install using following command:

composer require yajra/laravel-datatables-oracle

After that you need to set providers and alias.

config/app.php

.....

'providers' => [
....
Yajra\DataTables\DataTablesServiceProvider::class,
]

'aliases' => [
....
'DataTables' => Yajra\DataTables\Facades\DataTables::class,
]

.....

route/web.php

<?php

use Illuminate\Support\Facades\Route;
use App\Http\Controllers\CrudController;
use App\Http\Controllers\UserController;

Route::post('crud_insert', 'CrudController@save');
Route::post('crud_delete', 'CrudController@crud_delete');

Route::get('crud','CrudController@crud');
Route::get('crud_update/{id}','CrudController@crud_update');

Route::get('users', [CrudController::class, "index"])->name("users");

Create controller file : CrudController.php

<?php

  namespace App\Http\Controllers;

  use Illuminate\Http\Request;
  use App\CrudModel;
  use DataTables;

  class CrudController extends Controller
   {
    public function index(Request $request)
    {
      if ($request->ajax()) {
       $data = CrudModel::latest()->get();
       return Datatables::of($data)
       ->addIndexColumn()
       ->addColumn('action', function($row){

        $btn = '<button class="btn crud_delete btn-danger mr-3" id="'.$row->id.'"> X </button>
           <button id="'.$row->id.'" class="btn crud_update btn-warning"><i class="fa fa-pencil-square-o" aria-hidden="true"></i></button>';

       return $btn;
    })
    ->rawColumns(['action'])
    ->make(true);
  }

 return view('crud');
}

function save(Request $req){
  $data = new CrudModel;
  if(!empty($req->id)){
   $data->where("id",$req->id)
    ->update(['email' => $req->email,'password' => $req->pwd]);
    echo json_encode(array("success" => "Update"));
 }else{
  $data->email = $req->email;
  $data->password = $req->pwd;
  $data->save();
  echo json_encode(array("success" => "Insert"));
 }
}

function crud_delete(Request $req){
  $id = $req->id;
  $crud = CrudModel::find($id);
  $crud->delete();
  echo json_encode(array("success"=>"delete"));
}

function crud_update($id){
  $crud = CrudModel::where(array("id" => $id))->get();
  echo json_encode($crud[0]);
}
}

Create model file : CrudModel.php

<?php

  namespace App;

  use Illuminate\Database\Eloquent\Model;

  class CrudModel extends Model
  {
   protected $table = 'users';
   public $timestamps = false;
   protected $fillable = ['email', 'password'];
  }

Create view file : crud.blade.php

<!DOCTYPE html>
<html lang="en">
 <head>
  <title>Crud Form</title>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <meta name="csrf-token" content="{{ csrf_token() }}" />
  <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css">
  <link rel="stylesheet" href="https://www.jqueryscript.net/demo/Simple-Easy-jQuery-Notification-Plugin-NotifIt/css/notifIt.css">
  <script src="https://www.jqueryscript.net/demo/Simple-Easy-jQuery-Notification-Plugin-NotifIt/js/notifIt.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">
  <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-fluid mt-5">
   <h1 class="text-center">Crud Form</h1>
   <div class="row">
    <div class="col-md-6">
     <form id="crud" action="" method="post">
     @csrf
       <input type="hidden" name="id" id="id" value="">

       <label for="email2" class="mb-2 mr-sm-2">Email:</label>
       <input type="text" class="form-control mb-2 mr-sm-2" id="email" placeholder="Enter email" name="email" value="">
       <label for="pwd2" class="mb-2 mr-sm-2">Password:</label>
       <input type="text" class="form-control mb-2 mr-sm-2" id="pwd" placeholder="Enter password" name="pwd" value="">
       <input type="button" class="btn btn_submit btn-primary mb-2 shadow-none" value="Insert">
      </form>
    </div>
    <div class="col-md-6">
     <table class="table mt-3 data-table">
      <thead>
       <tr>
        <th>Id</th>
        <th>Email</th>
        <th>Password</th>
        <th>Action</th>
       </tr>
     </thead>
     <tbody>
     </tbody>
    </table>
   </div>
  </div>
</div>
</body>
<script>
 $(function () {
   $.ajaxSetup({
     headers: {
       'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
     }
  });

 var table = $('.data-table').DataTable({
  processing: true,
  serverSide: true,
  ajax: "{{ route('users') }}",
  columns: [
   {data: 'DT_RowIndex', name: 'DT_RowIndex'},
   {data: 'email', name: 'email'},
   {data: 'password', name: 'password'},
   {data: 'action', name: 'action', orderable: false, searchable: false},
 ]
});

$(document).ready(function(){

  $(".btn_submit").click(function(){
   if($("#email").val().trim() == 0){
     notif({
       msg: "Please Enter Email !",
       type: "error",
       position: "center"
  }); 
  $("#email").focus();
  return false;
}
else if($("#pwd").val().trim() == 0){
 notif({
  msg: "Please Enter Password !",
  type: "error",
  position: "center"
 }); 
 $("#pwd").focus();
 return false;
}
else{
 var formData = new FormData(crud);
 $.ajax({
  url: 'crud_insert',
  data: formData,
  processData: false,
  contentType: false,
  type: 'POST',
  success: function ( data ) {
  var obj = $.parseJSON(data);
  if(obj.success == "Insert"){
    $("#name").val("");
    $("#email").val("");
    $("#pwd").val("");
    notif({
     msg: "Insert Successfuly !",
     type: "success",
     position: "center"
   }); 
 }else if(obj.success == "Update"){
   $("#id").val("");
   $("#name").val("");
   $("#email").val("");
   $("#pwd").val("");
   $(".btn_submit").val("Insert");
     notif({
      msg: "Update Successfuly !",
      type: "success",
      position: "center"
     }); 
    }
   }
});
return false;
}
});

$(document).on("click",".crud_delete",function(){ 
 var c = confirm("Are you sure delete this item !");
 if (c == true) {
  var id = $(this).attr("id");
  $.ajax({
   context: this, 
   url: 'crud_delete',
   type: 'POST',
  data:{id:id},
  success: function ( data ) {
   var obj = $.parseJSON(data);
   if(obj.success == "delete"){
    table.draw();

   notif({
    msg: "Delete Successfuly !",
   type: "success",
   position: "center"
  }); 
 }
 }
});
}
return false;
});

$(document).on("click",".crud_update",function(){
 var id = $(this).attr("id");
 $.ajax({
  url:'crud_update/'+id,
  type:'get',
  success: function(data){
   var obj = $.parseJSON(data);
   console.log(obj);
   $("#id").val(obj.id);
   $("#email").val(obj.email);
   $("#pwd").val(obj.password);
   $(".btn_submit").val("Update");
  }
 });
  return false;
});
});
});
</script>
</html>