Laravel 5.8 DataTables Ajax Crud Tutorial

Laravel 5.8 DataTables Ajax Crud Tutorial – Today we will discuss how to create crud operation using the dataTable. We are going to show you how to create users list, create users, edit users and delete users with dataTable.

Today we are going to create users management using the yajra dataTables in laravel application. We will create easy crud operation using ajax.

Today we are create add, edit and delete using ajax without refresh (reload) a page. We will use yajra dataTables Draw function to displaying the list without refresh.

Contents

  • Install Laravel 5.8 Setup
  • Setup database
  • Database Migration
  • Install Yajra DataTables
  • Add Fake Data
  • Create Route, Controller & Blade View
  • Start Development Server
  • Conclusion

Install Laravel 5.8

First We need Download fresh Laravel 5.8 setup. Use the below command to download the laravel 5.8 fresh setup on your system.

composer create-project --prefer-dist laravel/laravel LaravelDemo

Setup Database

After successfully download laravel 5.8 Application, Go to your project .env file and set up database credential and move next step :

 DB_CONNECTION=mysql 
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE=here your database name here
DB_USERNAME=here database username here
DB_PASSWORD=here database password here

Database Migration

We need to do database migration of tables using below command:

php artisan migrate

This command will create neccessary tables in our database.

Install Yajra Datatables Package in Laravel

Now We will Install Yajra Datatables Packages in your laravel 5.8 application. Use the below command and install yajra packages in your laravel application.

composer require yajra/laravel-datatables-oracle

After successfully Install Yajra Datatables Packages, open config/app.php file and add service provider and alias.

 
config/app.php


'providers' => [


Yajra\Datatables\DatatablesServiceProvider::class,
],


'aliases' => [


'Datatables' => Yajra\Datatables\Facades\Datatables::class,
]

After set providers and aliases then publish vendor run by following command.

php artisan vendor:publish

Add Fake Records

We need to add some fake records in database. Use the below command for add fake records in your database.

php artisan tinker

After run the php artisan tinker. Use the below command. This command will add 150 fake records in your database

factory(App\User::class, 150)->create();

Create Route, Controller & Blade View

Add Route

Now we will add routes in web.php file as like below.

Open routes/web.php file

 Route::resource('ajax-crud-list', 'UsersController');
Route::post('ajax-crud-list/store', '[email protected]');
Route::get('ajax-crud-list/delete/{id}', '[email protected]');

Create Controller

We need to create new controller UsersController that will manage two method. lets use this below command and create Controller.

php artisan make:controller UsersController

Now open the controller let’s go to the => app/Http/Controllers/UsersController.php. Now create some methods for add user, edit user and delete user.

<?php

namespace App\Http\Controllers;

use App\User;
use Illuminate\Http\Request;
use Redirect,Response;

class UsersController extends Controller
{
/**
 * Display a listing of the resource.
 *
 * @return \Illuminate\Http\Response
 */
public function index()
{
    if(request()->ajax()) {
        return datatables()->of(User::select('*'))
        ->addColumn('action', 'action_button')
        ->rawColumns(['action'])
        ->addIndexColumn()
        ->make(true);
    }
    return view('list');
}


/**
 * Store a newly created resource in storage.
 *
 * @param  \Illuminate\Http\Request  $request
 * @return \Illuminate\Http\Response
 */
public function store(Request $request)
{  
    $userId = $request->user_id;
    $user   =   User::updateOrCreate(['id' => $userId],
                ['name' => $request->name, 'email' => $request->email]);        
    return Response::json($user);
}


/**
 * Show the form for editing the specified resource.
 *
 * @param  \App\Product  $product
 * @return \Illuminate\Http\Response
 */
public function edit($id)
{   
    $where = array('id' => $id);
    $user  = User::where($where)->first();

    return Response::json($user);
}


/**
 * Remove the specified resource from storage.
 *
 * @param  \App\Product  $product
 * @return \Illuminate\Http\Response
 */
public function destroy($id)
{
    $user = User::where('id',$id)->delete();

    return Response::json($user);
}
}

Create Blade View

First Create Button view

We need to create action_button.blade.php file. This file contain two button name edit and delete.

<a href="javascript:void(0)" data-toggle="tooltip"  data-id="{{ $id }}" data-original-title="Edit" class="edit btn btn-success edit-user">
	Edit
</a>
<a href="javascript:void(0);" id="delete-user" data-toggle="tooltip" data-original-title="Delete" data-id="{{ $id }}" class="delete btn btn-danger">
	Delete
</a>

Next, create list.blade.php file in resources/views/ folder and copy past following code.

<!DOCTYPE html>

<html lang="en">
<head>
<!-- CSRF Token -->
<meta name="csrf-token" content="{{ csrf_token() }}">
<title>Laravel DataTable Ajax Crud Tutorial - Tuts Make</title>
<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">
<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>
</head>
<body>

<div class="container">
<h2>Laravel DataTable Ajax Crud Tutorial - <a href="https://www.tutsmake.com" target="_blank">TutsMake</a></h2>
<br>
<a href="https://www.tutsmake.com/how-to-install-yajra-datatables-in-laravel/" class="btn btn-secondary">Back to Post</a>
<a href="javascript:void(0)" class="btn btn-info ml-3" id="create-new-user">Add New</a>
<br><br>

<table class="table table-bordered table-striped" id="laravel_datatable">
   <thead>
      <tr>
         <th>ID</th>
         <th>S. No</th>
         <th>Name</th>
         <th>Email</th>
         <th>Created at</th>
         <th>Action</th>
      </tr>
   </thead>
</table>
</div>

<div class="modal fade" id="ajax-crud-modal" aria-hidden="true">
<div class="modal-dialog">
<div class="modal-content">
    <div class="modal-header">
        <h4 class="modal-title" id="userCrudModal"></h4>
    </div>
    <div class="modal-body">
        <form id="userForm" name="userForm" class="form-horizontal">
           <input type="hidden" name="user_id" id="user_id">
            <div class="form-group">
                <label for="name" class="col-sm-2 control-label">Name</label>
                <div class="col-sm-12">
                    <input type="text" class="form-control" id="name" name="name" placeholder="Enter Name" value="" maxlength="50" required="">
                </div>
            </div>

            <div class="form-group">
                <label class="col-sm-2 control-label">Email</label>
                <div class="col-sm-12">
                    <input type="email" class="form-control" id="email" name="email" placeholder="Enter Email" value="" required="">
                </div>
            </div>
            <div class="col-sm-offset-2 col-sm-10">
             <button type="submit" class="btn btn-primary" id="btn-save" value="create">Save changes
             </button>
            </div>
        </form>
    </div>
    <div class="modal-footer">
       
    </div>
</div>
</div>
</div>
</body>
</html>

Script logic

Next we will create script tag and write some code for showing list, create user, edit user and delete user. In this script, put the below of after closing of body tag.

<script>
var SITEURL = '{{URL::to('')}}';
 $(document).ready( function () {
   $.ajaxSetup({
      headers: {
          'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
      }
  });
  $('#laravel_datatable').DataTable({
         processing: true,
         serverSide: true,
         ajax: {
          url: SITEURL + "ajax-crud-list",
          type: 'GET',
         },
         columns: [
                  {data: 'id', name: 'id', 'visible': false},
                  {data: 'DT_RowIndex', name: 'DT_RowIndex', orderable: false,searchable: false},
                  { data: 'name', name: 'name' },
                  { data: 'email', name: 'email' },
                  { data: 'created_at', name: 'created_at' },
                  {data: 'action', name: 'action', orderable: false},
               ],
        order: [[0, 'desc']]
      });
 /*  When user click add user button */
    $('#create-new-user').click(function () {
        $('#btn-save').val("create-user");
        $('#user_id').val('');
        $('#userForm').trigger("reset");
        $('#userCrudModal').html("Add New User");
        $('#ajax-crud-modal').modal('show');
    });

   /* When click edit user */
    $('body').on('click', '.edit-user', function () {
      var user_id = $(this).data('id');
      $.get('ajax-crud-list/' + user_id +'/edit', function (data) {
         $('#name-error').hide();
         $('#email-error').hide();
         $('#userCrudModal').html("Edit User");
          $('#btn-save').val("edit-user");
          $('#ajax-crud-modal').modal('show');
          $('#user_id').val(data.id);
          $('#name').val(data.name);
          $('#email').val(data.email);
      })
   });
    $('body').on('click', '#delete-user', function () {

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

        $.ajax({
            type: "get",
            url: SITEURL + "ajax-crud-list/delete/"+user_id,
            success: function (data) {
            var oTable = $('#laravel_datatable').dataTable(); 
            oTable.fnDraw(false);
            },
            error: function (data) {
                console.log('Error:', data);
            }
        });
    });   
   });

if ($("#userForm").length > 0) {
      $("#userForm").validate({

     submitHandler: function(form) {

      var actionType = $('#btn-save').val();
      $('#btn-save').html('Sending..');
     
      $.ajax({
          data: $('#userForm').serialize(),
          url: SITEURL + "ajax-crud-list/store",
          type: "POST",
          dataType: 'json',
          success: function (data) {

              $('#userForm').trigger("reset");
              $('#ajax-crud-modal').modal('hide');
              $('#btn-save').html('Save Changes');
              var oTable = $('#laravel_datatable').dataTable();
              oTable.fnDraw(false);
             
          },
          error: function (data) {
              console.log('Error:', data);
              $('#btn-save').html('Save Changes');
          }
      });
    }
  })
}
</script>

Start Development Server

We need to start development server. Use the php artisan serve command and start your server :

 php artisan serve
If you want to run the project diffrent port so use this below command
php artisan serve --port=8080

Now we are ready to run our example so run bellow command to quick run.

 http://localhost:8000/
Or direct hit in your browser
http://localhost/LaravelDemo/public/ajax-crud-list

Conclusion

In this laravel datatables ajax crud tutorial , We have successfully create a list using yajra datatables and also created add, edit, delete functionality without reloading the page.

If you have any questions or thoughts to share, use the comment form below to reach us.

Spread the love

3 Comments

  1. Monileak said:

    good tutorial. thanks bro.

    March 27, 2019
    Reply
  2. Mauricio Muñoz said:

    Excelente,, conciso.
    Gracias

    March 30, 2019
    Reply
  3. Adib said:

    tutorial e masuk pak eko

    May 12, 2019
    Reply

Leave a Reply

Your email address will not be published. Required fields are marked *