Friday, 13 September 2019

Laravel 6 Ajax Crud Tutorial Using DataTables Js With E.g.

laravel 6 DataTables Ajax Crud Tutorial – Today we are going to show, how to create crud operation using the yajra dataTable in laravel. We are going to show you how to create a product list, create the product, edit product and delete product with dataTable.
Today we are going to create product management using the yajra dataTables in laravel application. We will create easy laravel datatables crud operation using ajax.
Today we will create add, edit and delete using ajax without refresh (reload) a page on laravel datatables. We will use yajra dataTables Draw function to displaying the list without refresh.

Laravel DataTables Ajax Crud

Contents

  • Install laravel 6 Setup
  • Setup database
  • Database Migration
  • Install Yajra DataTables
  • Create Route, Controller & Blade View
  • Start Development Server
  • Conclusion

Install Laravel

First We need Download fresh Laravel setup. Use the below command to download the laravel 6 fresh setup on your system.
composer create-project --prefer-dist laravel/laravel blog

Setup Database

After successfully download laravel 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 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
  1. 'providers' => [
  2. Yajra\Datatables\DatatablesServiceProvider::class,
  3. ],
  4. 'aliases' => [
  5. 'Datatables' => Yajra\Datatables\Facades\Datatables::class,
  6. ]
After set providers and aliases then publish vendor run by the following command.
php artisan vendor:publish

Create CRB (Controller, Route, Blade)

Add Route
Now we will add routes in web.php file as like below.
Open routes/web.php file
 Route::get('product-list', 'ProductController@index');
 Route::get('product-list/{id}/edit', 'ProductController@edit');
 Route::post('product-list/store', 'ProductController@store');
 Route::get('product-list/delete/{id}', 'ProductController@destroy');

Create Controller

We need to create a new controller ProductController that will manage two methods. lets use this below command and create a Controller.
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 user, edit user and delete the user.
  1. <?php
  2. namespace App\Http\Controllers;
  3. use App\Product;
  4. use Illuminate\Http\Request;
  5. use Redirect,Response;
  6. class ProductController extends Controller
  7. {
  8. /**
  9. * Display a listing of the resource.
  10. *
  11. * @return \Illuminate\Http\Response
  12. */
  13. public function index()
  14. {
  15. if(request()->ajax()) {
  16. return datatables()->of(Product::select('*'))
  17. ->addColumn('action', 'DataTables.action')
  18. ->rawColumns(['action'])
  19. ->addIndexColumn()
  20. ->make(true);
  21. }
  22. return view('list');
  23. }
  24. /**
  25. * Store a newly created resource in storage.
  26. *
  27. * @param \Illuminate\Http\Request $request
  28. * @return \Illuminate\Http\Response
  29. */
  30. public function store(Request $request)
  31. {
  32. $productId = $request->product_id;
  33. $product = Product::updateOrCreate(['id' => $productId],
  34. ['title' => $request->title, 'product_code' => $request->product_code, 'description' => $request->description]);
  35. return Response::json($product);
  36. }
  37. /**
  38. * Show the form for editing the specified resource.
  39. *
  40. * @param \App\Product $product
  41. * @return \Illuminate\Http\Response
  42. */
  43. public function edit($id)
  44. {
  45. $where = array('id' => $id);
  46. $product = Product::where($where)->first();
  47. return Response::json($product);
  48. }
  49. /**
  50. * Remove the specified resource from storage.
  51. *
  52. * @param \App\Product $product
  53. * @return \Illuminate\Http\Response
  54. */
  55. public function destroy($id)
  56. {
  57. $product = Product::where('id',$id)->delete();
  58. return Response::json($product);
  59. }
  60. }

Create Blade View

First Create Button view
We need to create an action.blade.php file. This file contains two buttons name edit and delete.
  1. <a href="javascript:void(0)" data-toggle="tooltip" data-id="{{ $id }}" data-original-title="Edit" class="edit btn btn-success edit-product">
  2. Edit
  3. </a>
  4. <a href="javascript:void(0);" id="delete-product" data-toggle="tooltip" data-original-title="Delete" data-id="{{ $id }}" class="delete btn btn-danger">
  5. Delete
  6. </a>
Next, create a list.blade.php file in resources/views/ folder and copy past the following code.
  1. <!DOCTYPE html>
  2. <html lang="en">
  3. <head>
  4. <!-- CSRF Token -->
  5. <meta name="csrf-token" content="{{ csrf_token() }}">
  6. <title>Laravel DataTable Ajax Crud Tutorial</title>
  7. <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/4.1.3/css/bootstrap.min.css" />
  8. <link href="https://cdn.datatables.net/1.10.16/css/jquery.dataTables.min.css" rel="stylesheet">
  9. <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.js"></script>
  10. <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery-validate/1.19.0/jquery.validate.js"></script>
  11. <script src="https://cdn.datatables.net/1.10.16/js/jquery.dataTables.min.js"></script>
  12. <script src="https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/js/bootstrap.min.js"></script>
  13. </head>
  14. <body>
  15. <div class="container">
  16. <a href="javascript:void(0)" class="btn btn-info ml-3" id="create-new-product">Add New</a>
  17. <br><br>
  18. <table class="table table-bordered table-striped" id="laravel_datatable">
  19. <thead>
  20. <tr>
  21. <th>ID</th>
  22. <th>S. No</th>
  23. <th>Title</th>
  24. <th>Product Code</th>
  25. <th>Description</th>
  26. <th>Created at</th>
  27. <th>Action</th>
  28. </tr>
  29. </thead>
  30. </table>
  31. </div>
  32. <div class="modal fade" id="ajax-product-modal" aria-hidden="true">
  33. <div class="modal-dialog">
  34. <div class="modal-content">
  35. <div class="modal-header">
  36. <h4 class="modal-title" id="productCrudModal"></h4>
  37. </div>
  38. <div class="modal-body">
  39. <form id="productForm" name="productForm" class="form-horizontal">
  40. <input type="hidden" name="product_id" id="product_id">
  41. <div class="form-group">
  42. <label for="name" class="col-sm-2 control-label">Title</label>
  43. <div class="col-sm-12">
  44. <input type="text" class="form-control" id="title" name="title" placeholder="Enter Tilte" value="" maxlength="50" required="">
  45. </div>
  46. </div>
  47. <div class="form-group">
  48. <label for="name" class="col-sm-2 control-label">Product Code</label>
  49. <div class="col-sm-12">
  50. <input type="text" class="form-control" id="product_code" name="product_code" placeholder="Enter Tilte" value="" maxlength="50" required="">
  51. </div>
  52. </div>
  53. <div class="form-group">
  54. <label class="col-sm-2 control-label">Description</label>
  55. <div class="col-sm-12">
  56. <input type="text" class="form-control" id="description" name="description" placeholder="Enter Description" value="" required="">
  57. </div>
  58. </div>
  59. <div class="col-sm-offset-2 col-sm-10">
  60. <button type="submit" class="btn btn-primary" id="btn-save" value="create">Save changes
  61. </button>
  62. </div>
  63. </form>
  64. </div>
  65. <div class="modal-footer">
  66. </div>
  67. </div>
  68. </div>
  69. </div>
  70. </body>

  71. </html>

Script logic

Next, we will create a script tag and write some code for showing list, create a product, edit product and delete the product. In this script, put the below of after closing of the body tag.
  1. <script>
  2. var SITEURL = '{{URL::to('')}}';
  3. $(document).ready( function () {
  4. $.ajaxSetup({
  5. headers: {
  6. 'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
  7. }
  8. });
  9. $('#laravel_datatable').DataTable({
  10. processing: true,
  11. serverSide: true,
  12. ajax: {
  13. url: SITEURL + "product-list",
  14. type: 'GET',
  15. },
  16. columns: [
  17. {data: 'id', name: 'id', 'visible': false},
  18. {data: 'DT_RowIndex', name: 'DT_RowIndex', orderable: false,searchable: false},
  19. { data: 'title', name: 'title' },
  20. { data: 'product_code', name: 'product_code' },
  21. { data: 'description', name: 'description' },
  22. { data: 'created_at', name: 'created_at' },
  23. {data: 'action', name: 'action', orderable: false},
  24. ],
  25. order: [[0, 'desc']]
  26. });

  27. /* When user click add user button */
  28. $('#create-new-product').click(function () {
  29. $('#btn-save').val("create-product");
  30. $('#product_id').val('');
  31. $('#productForm').trigger("reset");
  32. $('#productCrudModal').html("Add New Product");
  33. $('#ajax-product-modal').modal('show');
  34. });
  35. /* When click edit user */
  36. $('body').on('click', '.edit-product', function () {
  37. var product_id = $(this).data('id');
  38. $.get('product-list/' + product_id +'/edit', function (data) {
  39. $('#title-error').hide();
  40. $('#product_code-error').hide();
  41. $('#description-error').hide();
  42. $('#productCrudModal').html("Edit Product");
  43. $('#btn-save').val("edit-product");
  44. $('#ajax-product-modal').modal('show');
  45. $('#product_id').val(data.id);
  46. $('#title').val(data.title);
  47. $('#product_code').val(data.product_code);
  48. $('#description').val(data.description);
  49. })
  50. });

  51. $('body').on('click', '#delete-product', function () {
  52. var product_id = $(this).data("id");
  53. if(confirm("Are You sure want to delete !")){
  54. $.ajax({
  55. type: "get",
  56. url: SITEURL + "product-list/delete/"+product_id,
  57. success: function (data) {
  58. var oTable = $('#laravel_datatable').dataTable();
  59. oTable.fnDraw(false);
  60. },
  61. error: function (data) {
  62. console.log('Error:', data);
  63. }
  64. });
  65. }
  66. });
  67. });
  68. if ($("#productForm").length > 0) {
  69. $("#productForm").validate({
  70. submitHandler: function(form) {
  71. var actionType = $('#btn-save').val();
  72. $('#btn-save').html('Sending..');
  73. $.ajax({
  74. data: $('#productForm').serialize(),
  75. url: SITEURL + "product-list/store",
  76. type: "POST",
  77. dataType: 'json',
  78. success: function (data) {
  79. $('#productForm').trigger("reset");
  80. $('#ajax-product-modal').modal('hide');
  81. $('#btn-save').html('Save Changes');
  82. var oTable = $('#laravel_datatable').dataTable();
  83. oTable.fnDraw(false);
  84. },
  85. error: function (data) {
  86. console.log('Error:', data);
  87. $('#btn-save').html('Save Changes');
  88. }
  89. });
  90. }
  91. })
  92. }
  93. </script>

Start Development Server

We need to start 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 datatables ajax crud tutorial, We have successfully create 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.

No comments:

Post a Comment