Laravel 6 AJAX CRUD Operation

This tutorial explains you to build CRUD example in Laravel 6 using Bootstrap, jQuery, AJAX etc.

For basic setup of Laravel 6 CRUD operation, please refer LARAVEL 6 CRUD operation tutorial.

In this tutorial, we already assume, you have done with LARAVEL 6 CRUD Operation.

Now, we will setup different Controller and View for same Database Migration.

Install Yajra Datatables Package

For this, we have to install yajra datatable package to this Laravel Installation.

Run below command to install Yajra Datatables Package

composer require yajra/laravel-datatables-oracle

After, successfully installation open “config/app.php” file add below code in providers and aliases array.

Providers Array:

Yajra\DataTables\DataTablesServiceProvider::class,

Aliases Array:

'DataTables' => Yajra\DataTables\Facades\DataTables::class,

Add Route

Now, open ‘routes/web.php’ and define the following route:

routes:web.php
Route::resource('tasks','TaskController');

Add Controller

Now, create the TaskAjaxController. For this, run the following command:

php artisan make:controller TaskAjaxController --resource

When you run this command then it will create the file in the following path:

app/Http/Controllers/TaskAjaxController.php

Now, include Task model and Datatables Package to the Controller

use App\Task;
use DataTables;

Now, write the following code into index() method:

public function index(Request $request)
{
if ($request->ajax()) {
$data = Task::latest()->get();
return Datatables::of($data)
->addIndexColumn()
->addColumn('action', function($row){
$btn = '<a href="javascript:void(0)" data-id="'.$row->id.'" title="Edit" class="edit btn btn-primary btn-sm edit-tasks">Edit</a>';
$btn = $btn.' <a href="javascript:void(0)" data-id="'.$row->id.'" title="Delete" class="btn btn-danger btn-sm delete-tasks">Delete</a>';
return $btn;
})
->rawColumns(['action'])
->make(true);
}
return view('tasks-ajax/index');
}

After that including following library to the “layout.blade.php

<meta name="csrf-token" content="{{ csrf_token() }}">
<link href="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/css/bootstrap.min.css" rel="stylesheet" >
<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>

Write below code in “tasks-ajax/index.blade.php

@extends('layout')

@section('content')
<div class="row">
<div class="col-lg-12 margin-tb">
<div class="pull-left">
<h2>List of Tasks</h2>
</div>
<div class="pull-right">
<a class="btn btn-success" id="create-task" href="javascript:void(0)"> Create New Task</a>
</div>
</div>
</div>

@if ($message = Session::get('success'))
<div class="alert alert-success">
<p>{{ $message }}</p>
</div>
@endif

<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 class="modal fade" id="ajax-model" aria-hidden="true">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<h4 class="modal-title" id="model-heading"></h4>
</div>
<div class="modal-body">
<form id="task-form" name="task-form" class="form-horizontal">
<input type="hidden" name="task_id" id="task_id">
<div class="form-group">
<label for="name" class="col-sm-2 control-label">Title</label>
<div class="col-sm-12">
<input type="text" class="form-control" id="title" name="title" placeholder="Please Enter Title" value="" maxlength="50" 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="Please 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="save-btn" value="create">Save</button>
</div>
</form>
</div>
</div>
</div>
</div>


<script type="text/javascript">
jQuery(function () {

jQuery.ajaxSetup({
headers: {
'X-CSRF-TOKEN': jQuery('meta[name="csrf-token"]').attr('content')
}
});

var table = jQuery('.data-table').DataTable({
processing: true,
serverSide: true,
ajax: "{{ route('tasks-ajax.index') }}",
columns: [
{data: 'DT_RowIndex', name: 'DT_RowIndex'},
{data: 'title', name: 'title'},
{data: 'description', name: 'description'},
{data: 'action', name: 'action', orderable: false, searchable: false},
]
});

jQuery('#create-task').click(function () {
jQuery('#save-btn').val("create");
jQuery('#save-btn').html("Save");
jQuery('#task_id').val('');
jQuery('#task-form').trigger("reset");
jQuery('#model-heading').html("Create New Task");
jQuery('#ajax-model').modal('show');
});

jQuery('body').on('click', '.edit-tasks', function () {
var task_id = jQuery(this).data('id');
jQuery.get("{{ route('tasks-ajax.index') }}" +'/' + task_id +'/edit', function (data) {
jQuery('#model-heading').html("Edit Task");
jQuery('#save-btn').val("edit");
jQuery('#save-btn').html("Save");
jQuery('#ajax-model').modal('show');
jQuery('#task_id').val(data.id);
jQuery('#title').val(data.title);
jQuery('#description').val(data.description);
})
});

jQuery('#save-btn').click(function (e) {
e.preventDefault();
jQuery(this).html('Sending..');

jQuery.ajax({
data: jQuery('#task-form').serialize(),
url: "{{ route('tasks-ajax.store') }}",
type: "POST",
dataType: 'json',
success: function (data) {

jQuery('#task-form').trigger("reset");
jQuery('#ajax-model').modal('hide');
table.draw();

},
error: function (data) {
console.log('Error:', data);
jQuery('#save-btn').html('Save');
}
});
});

jQuery('body').on('click', '.delete-tasks', function () {

var task_id = jQuery(this).data("id");
confirm("Are You sure want to delete !");

jQuery.ajax({
type: "DELETE",
url: "{{ route('tasks-ajax.store') }}"+'/'+task_id,
success: function (data) {
table.draw();
},
error: function (data) {
console.log('Error:', data);
}
});
});

});
</script>
@endsection

Respectively, add following code for edit, update and delete method.

public function store(Request $request)
{
Task::updateOrCreate(['id' => $request->task_id],
['title' => $request->title, 'description' => $request->description]);

return response()->json(['success'=>'Task saved successfully!']);
}


public function edit($id)
{
$task = Task::find($id);
return response()->json($task);
}

public function destroy($id)
{
Task::find($id)->delete();
return response()->json(['success'=>'Task deleted!']);
}

Now, run following command and open “http://127.0.0.1:8000/tasks-ajax” URL:

php artisan serve

Please  click here for Github code.