Laravel Ajax Datatable CRUD


Making ajax based CRUD operation system on the web application is very popular. It's very easy to make ajax based CRUD system with jQuery datatables plugin. jQuery datatables plugins have a lot of useful feature by default like live searching data, sorting data, pagination and more. If you want to use jQuery datatables with your laravel application for making ajax CRUD, this step by step tutorial will help you to do Ajax CRUD with datatables.

 

Laravel Ajax CRUD using yajra/laravel-datatables

  1. Make model and migration file.
  2. Install the laravel-datatables package.
  3. Define the route for CRUD.
  4. Make a controller for the CRUD system.
  5. Make view and add Js libraries.
  6. Js code for Ajax CRUD operation.

 

datatables-crud-example

 

1. Make a model and migration file.

We'll make a customer CRUD operation using jQuery datatables and Laravel framework. We need a database table to insert, update, delete records. To do that make a Laravel model and migration file using the artisan command.

php artisan make:model Customer -m

now create a migration file inside the database/migrations directory with the name given below.

2021_06_01_1622522461_create_customers_table.php
<?php

use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;

class CreateCustomersTable extends Migration
{
    public function up()
    {
        Schema::create('customers', function (Blueprint $table) {

		$table->increments(id)->unsigned();
		$table->string('name',50)->nullable()->default('NULL');
		$table->string('phone',50)->nullable()->default('NULL');
		$table->date('dob')->nullable()->default('NULL');
		$table->primary('id');

        });
    }

    public function down()
    {
        Schema::dropIfExists('customers');
    }
}

 Now run the migration via the artisan command below.

php artisan migrate

 

2. Install the laravel-datatables package

We have to Install the yajra/laravel-datatables package via composer command. During installation keep a stable internet connection.

composer require yajra/laravel-datatables-oracle:"~9.0"

 

3. Define the route for CRUD

Now let's define a resource route into the web.php route file. You can change the route endpoints according to your application.

Route::resource('customers','CustomerController');

 

4. Make a controller for the CRUD system

Now make a controller to handle the view and feed data to our jQuery datatables. Run the artisan command below to make a controller.

php artisan make:controller CustomerController

Do code in the controller:

<?php
namespace App\Http\Controllers;

use App\Customer;
use Illuminate\Http\Request;

class CustomerController extends Controller
{

    public function index(Request $request)
    {
        if ($request->ajax()) {
            $customers = Customer::all();
            return datatables()->of($customers)
                ->addColumn('action', function ($row) {
                    $html = '<a href="#" class="btn btn-xs btn-secondary btn-edit">Edit</a> ';
                    $html .= '<button data-rowid="' . $row->id . '" class="btn btn-xs btn-danger btn-delete">Del</button>';
                    return $html;
                })->toJson();
        }

        return view('customers.index');
    }

    public function store(Request $request)
    {
        // do validation
        Customer::create($request->all());
        return ['success' => true, 'message' => 'Inserted Successfully'];
    }

    public function show($id)
    {
        return;
    }

    public function update($id)
    {
        // do validation
        Customer::find($id)->update(request()->all());
        return ['success' => true, 'message' => 'Updated Successfully'];
    }

    public function destroy($id)
    {
        Customer::find($id)->delete();
        return ['success' => true, 'message' => 'Deleted Successfully'];
    }
}

 

5. Make view and add Js libraries.

Make a customers.blade.php view inside the resources/views directory and add js dependencies.

@extends('layouts.app')

@section('content')
<div class="container">
    <div class="row">
        <div class="col-md-8">

            <h3>Customers
                <button type="button" class="btn btn-xs btn-primary float-right add">Add Customer</button>
            </h3>
            <hr>

            <table id="customers" class="table table-bordered table-condensed table-striped">
                <thead>
                    <tr>
                        <th>ID</th>
                        <th>Name</th>
                        <th>Phone</th>
                        <th>DOB</th>
                        <th width="70">Action</th>
                    </tr>
                </thead>

            </table>


            <!--  -->
            <div class="modal" tabindex="-1" role="dialog">
                <div class="modal-dialog" role="document">
                    <form class="form" action="" method="POST">
                        <div class="modal-content">
                            <div class="modal-header">
                                <h5 class="modal-title">New Customer</h5>
                                <button type="button" class="close" data-dismiss="modal" aria-label="Close">
                                    <span aria-hidden="true">&times;</span>
                                </button>
                            </div>
                            <div class="modal-body">
                                <input type="hidden" name="id">

                                <div class="form-group">
                                    <label for="name">Name</label>
                                    <input type="text" name="name" class="form-control input-sm">
                                </div>
                                <div class="form-group">
                                    <label for="phone">Phone</label>
                                    <input type="text" name="phone" class="form-control input-sm">
                                </div>
                                <div class="form-group">
                                    <label for="dob">DOB</label>
                                    <input type="date" name="dob" class="form-control input-sm">
                                </div>
                            </div>
                            <div class="modal-footer">
                                <button type="button" class="btn btn-primary btn-save">Save</button>
                                <button type="button" class="btn btn-primary btn-update">Update</button>
                                <button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button>
                            </div>
                        </div>
                    </form>
                </div>
            </div>
            <!--  -->


            <link href="https://cdn.datatables.net/1.10.12/css/jquery.dataTables.min.css" rel="stylesheet">
            <script src="https://cdn.datatables.net/1.10.12/js/jquery.dataTables.min.js"></script>

            <!--js code here-->
            
        </div>
    </div>
</div>
@endsection

N.B We have used Bootstrap CSS for styling the view.

 Add the jQuery library and Bootstrap CSS into your layouts/app.blade.php file.

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.2.4/jquery.min.js"></script>

<!-- Bootstrap -->
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.12.9/umd/popper.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/js/bootstrap.min.js"></script>

<!-- Fonts -->
<link rel="dns-prefetch" href="//fonts.gstatic.com">
<link href="https://fonts.googleapis.com/css?family=Nunito" rel="stylesheet">

 

6. Js code for Ajax CRUD operation

Now add this js code for making ajax based CRUD at the end of the view file or using a separate js file.

<script>
    $(document).ready(function() {
        $.noConflict();
        var token = ''
        var modal = $('.modal')
        var form = $('.form')
        var btnAdd = $('.add'),
            btnSave = $('.btn-save'),
            btnUpdate = $('.btn-update');
        
        var table = $('#customers').DataTable({
                ajax: '',
                serverSide: true,
                processing: true,
                aaSorting:[[0,"desc"]],
                columns: [
                    {data: 'id', name: 'id'},
                    {data: 'name', name: 'name'},
                    {data: 'phone', name: 'phone'},
                    {data: 'dob', name: 'dob'},
                    {data: 'action', name: 'action'},
                ]
            });

        btnAdd.click(function(){
            modal.modal()
            form.trigger('reset')
            modal.find('.modal-title').text('Add New')
            btnSave.show();
            btnUpdate.hide()
        })

        btnSave.click(function(e){
            e.preventDefault();
            var data = form.serialize()
            console.log(data)
            $.ajax({
                type: "POST",
                url: "",
                data: data+'&_token='+token,
                success: function (data) {
                    if (data.success) {
                        table.draw();
                        form.trigger("reset");
                        modal.modal('hide');
                    }
                    else {
                        alert('Delete Fail');
                    }
                }
             }); //end ajax
        })

       
        $(document).on('click','.btn-edit',function(){
            btnSave.hide();
            btnUpdate.show();

            
            modal.find('.modal-title').text('Update Record')
            modal.find('.modal-footer button[type="submit"]').text('Update')

            var rowData =  table.row($(this).parents('tr')).data()
            
            form.find('input[name="id"]').val(rowData.id)
            form.find('input[name="name"]').val(rowData.name)
            form.find('input[name="phone"]').val(rowData.phone)
            form.find('input[name="dob"]').val(rowData.dob)

            modal.modal()
        })

        btnUpdate.click(function(){
            if(!confirm("Are you sure?")) return;
            var formData = form.serialize()+'&_method=PUT&_token='+token
            var updateId = form.find('input[name="id"]').val()
            $.ajax({
                type: "POST",
                url: "/" + updateId,
                data: formData,
                success: function (data) {
                    if (data.success) {
                        table.draw();
                        modal.modal('hide');
                    }
                }
             }); //end ajax
        })
            

        $(document).on('click','.btn-delete',function(){
            if(!confirm("Are you sure?")) return;

            var rowid = $(this).data('rowid')
            var el = $(this)
            if(!rowid) return;

            
            $.ajax({
                type: "POST",
                dataType: 'JSON',
                url: "/" + rowid,
                data: {_method: 'delete',_token:token},
                success: function (data) {
                    if (data.success) {
                        table.row(el.parents('tr'))
                            .remove()
                            .draw();
                    }
                }
             }); //end ajax
        })
    })
</script>

Hope this tutorial will help you to make ajax based CRUD operation in your Laravel application by using popular jQuery datatables plugins. If you find this tutorial helpful then please share it with others.


Share on




Related Post - Latest Post


Laravel Barcode generation tutorial

Laravel 8 CRUD example - Step by step

Laravel Inertia Js CRUD tutorial

Laravel 7 CRUD tutorial

Laravel Livewire CRUD tutorial

Laravel 6 jQuery Ajax CRUD tutorial