Laravel 6 Ajax CRUD(DataTables Js) Tutorial Example

Laravel 6 Ajax CRUD(DataTables Js) Tutorial Example

laravel 6 Crud Ajax DataTables Ajax Tutorial Example – In this tutorial, we would love to show, how to you can create crud operation using the yajra dataTable with laravel framework. Here, we will create product management listing using dataTable js like product list, create a product, edit product and delete product with Yajra dataTable.

Today we are show you how you can create product management using the yajra dataTables in laravel based application or project. We will create easy laravel datatables crud operation using datatable js step by step.

Create your first laravel crud ajax application using dataTables js . Learn step by step create ajax crud app using the dataTable js.

Laravel Crud Ajax Using DataTables Js

Contents

  • Install Fresh laravel 6 Setup
  • Set database Credentials
  • Use Database Migration
  • Install Yajra DataTables In App
  • Create Route, Controller & Blade View
  • Run Development Server
  • Conclusion

Install Fresh Laravel Setup

In this step, we will install a fresh new setup in our system. Use the laravel composer command to download fresh new setup in your system. The command is given below:

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

Set database Credentials

Next step, you have downloaded the fresh new setup of laravel in your system. So set the database credentials in your application. Let’s open your project .env file and set the database credentials here.

 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

Use Database Migration

In this step, we will migrate tables into your database. We will give the database migration command below:

php artisan migrate

This command will create necessary tables in our database.

Install Yajra Datatables Package in Laravel

Now We will Install Yajra Datatables Packages in your laravel 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 in your laravel application. Next step, open config/app.php file and add service provider and aliases.

 
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

Create (Controller, Route, Blade)

Add Route

In this step, we will add routes in the web.php file as below.

Let’s open routes/web.php file and update the below code here:

 Route::get('product-list', '[email protected]');
Route::get('product-list/{id}/edit', '[email protected]');
Route::post('product-list/store', '[email protected]');
Route::get('product-list/delete/{id}', '[email protected]');

Create Controller

We need to create a new controller ProductController. So use the below command and create a new controller that name is ProductController.

php artisan make:controller ProductController

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

In Product Controller, we need to create some methods:

  • Index()
  • Store()
  • Edit()
  • Destroy()

Index() method

Using the index() method, we will show the product list. So update the below code in your product controller index() method:

public function index()
{
    if(request()->ajax()) {
        return datatables()->of(Product::select('*'))
        ->addColumn('action', 'DataTables.action')
        ->rawColumns(['action'])
        ->addIndexColumn()
        ->make(true);
    }
    return view('list');
}

Store() Method

Using the Store() method, we will save and update the product into a database table. So update the below code in your product controller Store() method:

public function store(Request $request)
{  
    $productId = $request->product_id;
    $product   =   Product::updateOrCreate(['id' => $productId],
                ['title' => $request->title, 'product_code' => $request->product_code, 'description' => $request->description]);        
    return Response::json($product);
}

Edit() Method

Using the Edit() method, we will edit the product details, So update the below code with your edit method:

public function edit($id)
{   
    $where = array('id' => $id);
    $product  = Product::where($where)->first();
 
    return Response::json($product);
}

Delete() Method

Using the delete method, you can delete a product from the product list and also database table. So update the below code with your delete() method:

public function destroy($id)
{
    $product = Product::where('id',$id)->delete();
 
    return Response::json($product);
}

<?php
 
namespace App\Http\Controllers;
 
use App\Product;
use Illuminate\Http\Request;
use Redirect,Response;
 
class ProductController extends Controller
{
/**
 * Display a listing of the resource.
 *
 * @return \Illuminate\Http\Response
 */
public function index()
{
    if(request()->ajax()) {
        return datatables()->of(Product::select('*'))
        ->addColumn('action', 'DataTables.action')
        ->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)
{  
    $productId = $request->product_id;
    $product   =   Product::updateOrCreate(['id' => $productId],
                ['title' => $request->title, 'product_code' => $request->product_code, 'description' => $request->description]);        
    return Response::json($product);
}
 
 
/**
 * Show the form for editing the specified resource.
 *
 * @param  \App\Product  $product
 * @return \Illuminate\Http\Response
 */
public function edit($id)
{   
    $where = array('id' => $id);
    $product  = Product::where($where)->first();
 
    return Response::json($product);
}
 
 
/**
 * Remove the specified resource from storage.
 *
 * @param  \App\Product  $product
 * @return \Illuminate\Http\Response
 */
public function destroy($id)
{
    $product = Product::where('id',$id)->delete();
 
    return Response::json($product);
}
}

Create Blade View

In this step, we need to create two-blade views files. The first file is an action button that contains two buttons and the button name is edit and delete. The second file contains the product list.

Create a Button view

We need to create an action.blade.php file. This file contains a two-button name edit and delete. So you can update the below code in your action button file.

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

Next, create a list.blade.php file in resources/views/ folder and update the below code in your product list file.

<!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-product">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>Title</th>
         <th>Product Code</th>
         <th>Description</th>
         <th>Created at</th>
         <th>Action</th>
      </tr>
   </thead>
</table>
</div>
 
<div class="modal fade" id="ajax-product-modal" aria-hidden="true">
<div class="modal-dialog">
<div class="modal-content">
    <div class="modal-header">
        <h4 class="modal-title" id="productCrudModal"></h4>
    </div>
    <div class="modal-body">
        <form id="productForm" name="productForm" class="form-horizontal">
           <input type="hidden" name="product_id" id="product_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="Enter Tilte" value="" maxlength="50" required="">
                </div>
            </div> 
            <div class="form-group">
                <label for="name" class="col-sm-2 control-label">Product Code</label>
                <div class="col-sm-12">
                    <input type="text" class="form-control" id="product_code" name="product_code" placeholder="Enter Tilte" value="" maxlength="50" required="">
                </div>
            </div>
 
            <div class="form-group">
                <label class="col-sm-2 control-label">Description</label>
                <div class="col-sm-12">
                    <input type="text" class="form-control" id="description" name="description" placeholder="Enter Description" 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 Code

Next, we will create a script code for performing create, store, update and delete products from the database table products. In this script code, we will create the first code for showing the product list using the ajax. After that, we will create crud operation code. So update this code in your list.blade.php file:

<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 + "product-list",
          type: 'GET',
         },
         columns: [
                  {data: 'id', name: 'id', 'visible': false},
                  {data: 'DT_RowIndex', name: 'DT_RowIndex', orderable: false,searchable: false},
                  { data: 'title', name: 'title' },
                  { data: 'product_code', name: 'product_code' },
                  { data: 'description', name: 'description' },
                  { data: 'created_at', name: 'created_at' },
                  {data: 'action', name: 'action', orderable: false},
               ],
        order: [[0, 'desc']]
      });

 /*  When user click add user button */
    $('#create-new-product').click(function () {
        $('#btn-save').val("create-product");
        $('#product_id').val('');
        $('#productForm').trigger("reset");
        $('#productCrudModal').html("Add New Product");
        $('#ajax-product-modal').modal('show');
    });
 
   /* When click edit user */
    $('body').on('click', '.edit-product', function () {
      var product_id = $(this).data('id');
      $.get('product-list/' + product_id +'/edit', function (data) {
         $('#title-error').hide();
         $('#product_code-error').hide();
         $('#description-error').hide();
         $('#productCrudModal').html("Edit Product");
          $('#btn-save').val("edit-product");
          $('#ajax-product-modal').modal('show');
          $('#product_id').val(data.id);
          $('#title').val(data.title);
          $('#product_code').val(data.product_code);
          $('#description').val(data.description);
      })
   });

    $('body').on('click', '#delete-product', function () {
 
        var product_id = $(this).data("id");
       
        if(confirm("Are You sure want to delete !")){
          $.ajax({
              type: "get",
              url: SITEURL + "product-list/delete/"+product_id,
              success: function (data) {
              var oTable = $('#laravel_datatable').dataTable(); 
              oTable.fnDraw(false);
              },
              error: function (data) {
                  console.log('Error:', data);
              }
          });
        }
    }); 
  
   });
 
if ($("#productForm").length > 0) {
      $("#productForm").validate({
 
     submitHandler: function(form) {
 
      var actionType = $('#btn-save').val();
      $('#btn-save').html('Sending..');
      
      $.ajax({
          data: $('#productForm').serialize(),
          url: SITEURL + "product-list/store",
          type: "POST",
          dataType: 'json',
          success: function (data) {
 
              $('#productForm').trigger("reset");
              $('#ajax-product-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>

Run Development Server

We need to run the 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/product-list

Conclusion

In this laravel curd ajax dataTable tutorial, We have successfully created a product list using yajra data tables 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.

Leave a Reply

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