Laravel 5.8 DataTables Ajax Crud Tutorial

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', 'UsersController@store');
Route::get('ajax-crud-list/delete/{id}', 'UsersController@destroy');

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");
        if(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.

If you want to remove public or public/index.php from URL In laravel, Click Me

 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.

You may like

  1. Laravel 6 Tutorial From Scratch | Step By Step
  2. Laravel 6 Ajax CRUD(DataTables Js) Tutorial Example
  3. Laravel 6 – Ajax CRUD (Operation) Application Example
  4. Laravel 6 CRUD Example Tutorial (Step By Step)
  5. Laravel 6 Angular JS CRUD Example Tutorial

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

AuthorAdmin

My name is Devendra Dode. I am a full-stack developer, entrepreneur, and owner of Tutsmake.com. I like writing tutorials and tips that can help other developers. I share tutorials of PHP, Python, Javascript, JQuery, Laravel, Livewire, Codeigniter, Node JS, Express JS, Vue JS, Angular JS, React Js, MySQL, MongoDB, REST APIs, Windows, Xampp, Linux, Ubuntu, Amazon AWS, Composer, SEO, WordPress, SSL and Bootstrap from a starting stage. As well as demo example.

12 replies to Laravel 5.8 DataTables Ajax Crud Tutorial

  1. good tutorial. thanks bro.

  2. Excelente,, conciso.
    Gracias

  3. tutorial e masuk pak eko

  4. how about the update function?

    • Here store function is also work to insert and update data into database.

  5. Where and how you use the file “action_button.blade.php” ?

  6. Hello sir please make one video for laravel localization multiple languages

  7. how to edit URL on AJAX ??

  8. As the crud can be used in several tables,
    I mean being able to use it in products and also for users, as well as for suppliers and customers.

  9. Very Nice tutorial for beginners.i suggest for add ajax calling site url before slash.

  10. very good, thx)

  11. Nice

Leave a Reply

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