How to add Edit Delete button in Yajra DataTables – Laravel

In Laravel using Yajra DataTables package, you can easily add pagination in less time.

To add edit delete button in the DataTable need to use addColumn() method.

In this tutorial, I am assuming you have already installed the Yajra package, if not then you can view this tutorial.

I am implementing this on Laravel 9.

How to add Edit Delete button in Yajra DataTables – Laravel


Contents

  1. Add Database configuration
  2. Create a Table
  3. Create Model
  4. Create Controller
  5. Create Route
  6. Create View
  7. Output
  8. Conclusion

1. Add Database configuration

Open .env file to update the database connection.

Specify the host, database name, username, and password.

DB_CONNECTION=mysql
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE=tutorial
DB_USERNAME=root
DB_PASSWORD=

2. Create a Table

  • Create a new table employees using migration.
php artisan make:migration create_employees_table
  • Now, navigate to database/migrations/ folder from the project root.
  • Find a PHP file that ends with create_employees_table and open it.
  • Define the table structure in the up() method.
public function up()
{
    Schema::create('employees', function (Blueprint $table) {
       $table->id();
       $table->string('emp_name',60);
       $table->string('email',80);
       $table->string('gender',20);
       $table->string('city',100);
       $table->smallInteger('status',2);
       $table->timestamps();
    });
}
  • Run the migration –
php artisan migrate
  • The table is been created and I added some records to it.

3. Create Model

  • Create Employees Model –
php artisan make:model Employees
  • Open app/Models/Employees.php file.
  • Specify mass assignable Model attributes – emp_name, email, gender, city, and status using the $fillable property.

Completed Code

<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;

class Employees extends Model
{
    use HasFactory;
    protected $fillable = [ 
        'emp_name','email','gender','city','status'
    ];
}

4. Create Controller

  • Create PagesController controller.
php artisan make:controller PagesController
  • Import Employees model and DataTables.
  • Create 5 methods –
    • index() – Load index view.
    • getDataTableData() – Using this method load DataTable data.

Pass $employees in Datatables::of() to generate return response.

Using addColumn() add edit and delete buttons. In the edit button store employee id in data-id attribute and to open Bootstrap modal add data-bs-toggle and data-bs-target attribute.

In the delete button also store employee id in data-id attribute.

    • getEmployeeData() – Using this method fetch a record by POST id from employees table. Initialize $response Array with fetched data and return in JSON format.
    • updateEmployee() – Using this method update a employee record.
    • deleteEmployee() – Using this method delete a employee record by POST id.

Completed Code

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\Models\Employees;
use DataTables;

class PagesController extends Controller
{

     public function index(){
         return view('index');
     }

     // DataTable data
     public function getDataTableData(){
         $employees = Employees::select('*');

         return Datatables::of($employees)
            ->addIndexColumn()
            ->addColumn('status', function($row){

                 if($row->status == 1){
                      return "Active";
                 }else{
                      return "Inactive";
                 }

            }) 
            ->addColumn('action', function($row){

                 // Update Button
                 $updateButton = "<button class='btn btn-sm btn-info updateUser' data-id='".$row->id."' data-bs-toggle='modal' data-bs-target='#updateModal' ><i class='fa-solid fa-pen-to-square'></i></button>";

                 // Delete Button
                 $deleteButton = "<button class='btn btn-sm btn-danger deleteUser' data-id='".$row->id."'><i class='fa-solid fa-trash'></i></button>";

                 return $updateButton." ".$deleteButton;

            }) 
            ->make();
     }

     // Read Employee record by ID
     public function getEmployeeData(Request $request){

         ## Read POST data 
         $id = $request->post('id');

         $empdata = Employees::find($id);

         $response = array();
         if(!empty($empdata)){

             $response['emp_name'] = $empdata->emp_name;
             $response['email'] = $empdata->email;
             $response['city'] = $empdata->city;
             $response['gender'] = $empdata->gender;

             $response['success'] = 1;
         }else{
             $response['success'] = 0;
         }

         return response()->json($response);

     }

     // Update Employee record
     public function updateEmployee(Request $request){
         ## Read POST data
         $id = $request->post('id');

         $empdata = Employees::find($id);

         $response = array();
         if(!empty($empdata)){
              $updata['emp_name'] = $request->post('emp_name');
              $updata['email'] = $request->post('email');
              $updata['gender'] = $request->post('gender');
              $updata['city'] = $request->post('city');

              if($empdata->update($updata)){
                   $response['success'] = 1;
                   $response['msg'] = 'Update successfully'; 
              }else{
                   $response['success'] = 0;
                   $response['msg'] = 'Record not updated';
              }

         }else{
              $response['success'] = 0;
              $response['msg'] = 'Invalid ID.';
         }

         return response()->json($response); 
     }

     // Delete Employee
     public function deleteEmployee(Request $request){

         ## Read POST data
         $id = $request->post('id');

         $empdata = Employees::find($id);

         if($empdata->delete()){
             $response['success'] = 1;
             $response['msg'] = 'Delete successfully'; 
         }else{
             $response['success'] = 0;
             $response['msg'] = 'Invalid ID.';
         }

         return response()->json($response); 
     }

}

5. Create Route

  • Open routes/web.php file.
  • Create 5 routes –
    • / – Load index view.
    • /getdatatabledata – GET type route to fetch DataTable data.
    • /getEmployeeData – POST type route to fetch a record for displaying in Bootstrap modal for update.
    • /updateEmployee – POST type route to update a record.
    • /deleteEmployee – POST type route to delete a record.
<?php

use Illuminate\Support\Facades\Route;
use App\Http\Controllers\PagesController;

Route::get('/', [PagesController::class, 'datatableindex'])->name('datatableindex');
Route::get('/getdatatabledata', [PagesController::class, 'getDataTableData'])->name('getDataTableData');
Route::post('/getEmployeeData', [PagesController::class, 'getEmployeeData'])->name('getEmployeeData');
Route::post('/updateEmployee', [PagesController::class, 'updateEmployee'])->name('updateEmployee');
Route::post('/deleteEmployee', [PagesController::class, 'deleteEmployee'])->name('deleteEmployee');

6. Create View

Create index.blade.php file in views/ folder.

HTML

Store CSRF token in <meta > tag. Include jQuery, Bootstrap, and DataTable libraries.

Create a bootstrap modal to display edit form. Form fields auto-filled with data when clicking on the edit icon using jQuery AJAX.

Create <table id='empTable'> to initialize DataTable.


Script

Read CSRF token from <meta > tag and store in CSRF_TOKEN variable.

Initialize DataTable in #empTable. Set AJAX URL to route('getDataTableData') and specify keys name that needs to read in columns options.

  • Update –

Define click event on updateUser class. Read data-id attribute of the button and assign it to id variable. Update #txt_empid value with id variable.

Send AJAX request to route('getEmployeeData') and pass {_token: CSRF_TOKEN,id: id} as data to fetch a record and fill Bootstrap modal fields for the update.

Define click event on Bootstrap Modal save button #btn_save. Read all elements value and assign to the variables. If all elements has value then send AJAX request to route('updateEmployee') and pass {_token: CSRF_TOKEN,id: id,emp_name: emp_name, email: email, gender: gender, city: city} as data.

On successful callback check if response.success == 1. If it is means a record is updated successfully. Empty the Modal input element values and refresh the DataTable.

  • Delete –

Define click event on deleteUser class. Read data-id attribute of the button and assign it to id variable.

Send AJAX request to route('deleteEmployee') and pass {_token: CSRF_TOKEN,id: id} as data. On successful callback check if response.success == 1 . If it is means a record is deleted successfully and refresh the DataTable.

Completed Code

<!DOCTYPE html>
<html>
<head>
   <meta charset="utf-8">
   <meta name="viewport" content="width=device-width, initial-scale=1">
   <meta name="csrf-token" content="{{ csrf_token() }}">
   <title>How to add Edit Delete button in Yajra DataTables – Laravel</title>

   <link rel="stylesheet" type="text/css" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.2.0/css/all.min.css">
   <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@5.2.2/dist/css/bootstrap.min.css"/>
   <link rel="stylesheet" type="text/css" href="https://cdn.datatables.net/1.10.25/css/jquery.dataTables.min.css"/>

</head>
<body>
   <div class='container mt-5'>

       <!-- Modal -->
       <div id="updateModal" class="modal fade" role="dialog">
           <div class="modal-dialog">

               <!-- Modal content-->
              <div class="modal-content">
                  <div class="modal-header">
                      <h4 class="modal-title">Update</h4>
                      <button type="button" class="close" data-dismiss="modal">&times;</button> 
                  </div>
                  <div class="modal-body">
                      <div class="form-group">
                          <label for="name" >Employee Name</label>
                          <input type="text" class="form-control" id="emp_name" placeholder="Enter Employee name" required> 
                      </div>
                      <div class="form-group">
                          <label for="email" >Email</label> 
                          <input type="email" class="form-control" id="email" placeholder="Enter email"> 
                      </div> 
                      <div class="form-group">
                          <label for="gender" >Gender</label>
                          <select id='gender' class="form-control">
                              <option value='Male'>Male</option>
                              <option value='Female'>Female</option>
                          </select> 
                      </div> 
                     <div class="form-group">
                          <label for="city" >City</label> 
                          <input type="text" class="form-control" id="city" placeholder="Enter city"> 
                     </div>

                  </div>
                  <div class="modal-footer">
                      <input type="hidden" id="txt_empid" value="0">
                      <button type="button" class="btn btn-success btn-sm" id="btn_save">Save</button>
                      <button type="button" class="btn btn-default btn-sm" data-dismiss="modal">Close</button>
                  </div>
             </div>

           </div>
       </div>

       <!-- Table -->
       <table id='empTable' class='datatable'>
           <thead >
               <tr>
                   <td>Employee Name</td>
                   <td>Email</td>
                   <td>Gender</td>
                   <td>City</td>
                   <td>Status</td>
                   <td>Action</td>
               </tr>
           </thead>
       </table>
   </div>

   <!-- Script -->
   <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.1/jquery.min.js"></script>
   <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.2.2/dist/js/bootstrap.min.js"></script>
   <script src="https://cdn.datatables.net/1.10.25/js/jquery.dataTables.min.js"></script>
   <script type="text/javascript">
   // CSRF Token
   var CSRF_TOKEN = $('meta[name="csrf-token"]').attr('content'); 
   $(document).ready(function(){

       // Initialize
       var empTable = $('#empTable').DataTable({
             processing: true,
             serverSide: true,
             ajax: "{{ route('getDataTableData') }}",
             columns: [
                 { data: 'emp_name' },
                 { data: 'email' },
                 { data: 'gender' },
                 { data: 'city' },
                 { data: 'status' },
                 { data: 'action' },
             ]
       });

       // Update record
       $('#empTable').on('click','.updateUser',function(){
            var id = $(this).data('id');

            $('#txt_empid').val(id);

            // AJAX request
            $.ajax({
                url: "{{ route('getEmployeeData') }}",
                type: 'post',
                data: {_token: CSRF_TOKEN,id: id},
                dataType: 'json',
                success: function(response){

                    if(response.success == 1){

                         $('#emp_name').val(response.emp_name);
                         $('#email').val(response.email);
                         $('#gender').val(response.gender);
                         $('#city').val(response.city);

                         empTable.ajax.reload();
                    }else{
                         alert("Invalid ID.");
                    }
                }
            });

       });

       // Save user 
       $('#btn_save').click(function(){
            var id = $('#txt_empid').val();

            var emp_name = $('#emp_name').val().trim();
            var email = $('#email').val().trim();
            var gender = $('#gender').val().trim();
            var city = $('#city').val().trim();

            if(emp_name !='' && email != '' && city != ''){

                 // AJAX request
                 $.ajax({
                     url: "{{ route('updateEmployee') }}",
                     type: 'post',
                     data: {_token: CSRF_TOKEN,id: id,emp_name: emp_name, email: email, gender: gender, city: city},
                     dataType: 'json',
                     success: function(response){
                         if(response.success == 1){
                              alert(response.msg);

                              // Empty and reset the values
                              $('#emp_name','#email','#city').val('');
                              $('#gender').val('Male');
                              $('#txt_empid').val(0);

                              // Reload DataTable
                              empTable.ajax.reload();

                              // Close modal
                              $('#updateModal').modal('toggle');
                         }else{
                              alert(response.msg);
                         }
                     }
                 });

            }else{
                 alert('Please fill all fields.');
            }
       });

       // Delete record
       $('#empTable').on('click','.deleteUser',function(){
            var id = $(this).data('id');

            var deleteConfirm = confirm("Are you sure?");
            if (deleteConfirm == true) {
                 // AJAX request
                 $.ajax({
                     url: "{{ route('deleteEmployee') }}",
                     type: 'post',
                     data: {_token: CSRF_TOKEN,id: id},
                     success: function(response){
                          if(response.success == 1){
                               alert("Record deleted.");

                               // Reload DataTable
                               empTable.ajax.reload();
                          }else{
                                alert("Invalid ID.");
                          }
                     }
                 });
            }

       });

   });

   </script>
</body>
</html>

7. Output

View Output


8. Conclusion

You can similarly add more buttons or other HTML elements like – radio button, checkbox, textbox, etc. in the DataTables.

Make sure to redraw DataTables after performing action otherwise, changes not display in pagination.

If you found this tutorial helpful then don't forget to share.