In this tutorial you will learn about the Laravel 7/6 DataTable Ajax CRUD Example Tutorial and its application with practical example.
In this Laravel 7/6 Datatables CRUD operation example tutorial I’ll show you how to create a simple crud application using yajra Datatables in laravel 7/6. In this example we will learn how to create a simple crud operation application using Datatables in laravel 7/6. In this laravel 7/6 crud application we will be using jQuery and ajax to delete data from datatable crud app and MySQL database in laravel 7/6 app.
In this tutorial, you will learn to implement ajax based CRUD (Create, Read, Update and Delete) operations using datatable js. In this tutorial, we will be using yajra datatable package for listing of records with pagination, sorting and filter (search) feature.
Laravel 7/6 DataTable Ajax CRUD Example Tutorial
In this step by step guide, we will be creating a simple laravel 7/6 application to demonstrate you how to install yajra datatable package and implement ajax based CRUD operations with datatable js.
- Step 1: Install Fresh laravel Setup
- Step 2: Set database Credentials
- Step 3: Create Migration And Model
- Step 4: Install Yajra DataTables in App
- Step 5: Create Route, Controller & Blade View
- Step 6: Run Development Server
- Step 7: Live Demo
Step 1: Install Fresh Laravel Setup
First of all we need to create a fresh laravel project, download and install Laravel using the below command
1 |
composer create-project --prefer-dist laravel/laravel blog |
Step 2: Set database Credentials
Now, lets create a MySQL database and connect it with laravel application. After creating database we need to set database credential in application’s .env file.
1 2 3 4 5 6 |
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 |
Step 3: Create Migration And Model
Now, in this step we will create model and migration file. Please run the following command:
1 |
php artisan nake:modal Product -m |
Now go to database/migrations/ and open create_products_table.php file. Then put the following code into this file:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 |
<?php use Illuminate\Database\Migrations\Migration; use Illuminate\Database\Schema\Blueprint; use Illuminate\Support\Facades\Schema; class CreateProductsTable extends Migration { /** * Run the migrations. * * @return void */ public function up() { Schema::create('products', function (Blueprint $table) { $table->id(); $table->string('title'); $table->string('product_code'); $table->text('description'); $table->timestamps(); }); } /** * Reverse the migrations. * * @return void */ public function down() { Schema::dropIfExists('products'); } } |
Now, in this step we will create model and migration file. Please run the following command:
1 |
php artisan migrate |
The above command will create tables in your database. Now, go to App directory and open Product.php file and then update the following code to into Product.php file as follow
app\Product.php
1 2 3 4 5 6 7 8 9 10 11 |
<?php namespace App; use Illuminate\Database\Eloquent\Model; class Product extends Model { protected $fillable = ['title','product_code','description','image']; } |
Step 4: Install Yajra Datatables Package in Laravel
In this step, we will install Yajra Datatables Package via the composer dependency manager. Use the following command to install Yajra Datatables Package.
1 |
composer require yajra/laravel-datatables-oracle |
After Installing Yajra Datatables package, we need to add service provider and alias in config/app.php file as following.
config/app.php
1 2 3 4 5 6 7 8 9 10 11 12 |
'providers' => [ Yajra\Datatables\DatatablesServiceProvider::class, ], 'aliases' => [ 'Datatables' => Yajra\Datatables\Facades\Datatables::class, ] |
After set providers and aliases then publish vendor run by following command.
Step 5: Create (Controller, Route, Blade)
After this, we need to define routes in “routes/web.php” file. Lets open “routes/web.php” file and add the following routes in it.
routes/web.php
1 2 3 4 |
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'); |
2: Create Controller
Now, lets create a controller named ProductController using command given below –
1 |
php artisan make:controller ProductController |
Now, open app/Http/Controllers/ProductController.php and create some methods to add products, edit product and delete the product. In Product Controller, we need to create some methods:
- Index()
- Store()
- Edit()
- Destroy()
Index() method
1 2 3 4 5 6 7 8 9 10 11 |
public function index() { if(request()->ajax()) { return datatables()->of(Product::select('*')) ->addColumn('action', 'action') ->rawColumns(['action']) ->addIndexColumn() ->make(true); } return view('list'); } |
Store() Method
1 2 3 4 5 6 7 |
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
1 2 3 4 5 6 7 |
public function edit($id) { $where = array('id' => $id); $product = Product::where($where)->first(); return Response::json($product); } |
Delete() Method
1 2 3 4 5 6 |
public function destroy($id) { $product = Product::where('id',$id)->delete(); return Response::json($product); } |
Now, update all methods into your ProductController.php file as follow:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 |
<?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', '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); } } |
3: Create Blade View
Create a Button view
Now, we will create 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.
1 2 3 4 5 6 |
<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.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 |
<!DOCTYPE html> <html lang="en"> <head> <!-- CSRF Token --> <meta name="csrf-token" content="{{ csrf_token() }}"> <title>Laravel DataTable Ajax Crud Tutorial</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</h2> <br> <a href="https://www.yoursite.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
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 |
<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> |
Step 6: Run Development Server
Now we are ready to run our example so lets start the development server using following artisan command –
1 |
php artisan serve |
Now, open the following URL in browser to see the output –
1 |
http://localhost:8000/product-list |