Is there any easy way to create a dynamic multiple data delete function in Laravel?

Asked by Minji on 10 Apr 2019 1491 Views

Jiwan on 10 Apr 2019


Creating a single delete method that can delete any number of data from any table dynamically is a great idea while working on backend application.

Generally, Laravel delete method works wonder but it makes your task much easier if you could add a single method that works universally.

In the example below, Users table is used for reference.

Admin Controller

Create a method that'll store all the data from the users in a variable so that you can display them in your blade template when a route is requested.

// Route Example
Route::get('users','adminController@users');

// Controller Method  
public function users(){	
  $data = Users::all();
  return view ('allUsers',['data'=>$data]);
}	

Blade Template

Now, you can create a table in your blade template allUsers.blade.php in this example to display those data in a tabular format. Make sure you wrap them inside a <form> tag.

Here's an example.

<form method="post" action="{{url('multipleDelete')}}">
  {{ csrf_field() }}
  <input type="hidden" name="tablename" value="{{encrypt('users')}}">
  <input type="hidden" name="tableid" value="{{encrypt('id')}}">    
  <table class="table table-striped">
    <thead>
      <tr>
        <th><input type="checkbox" id="select-all"> Username</th>
        <th>Email</th>
        <th>Role</th>
      </tr>
    </thead>
    <tbody>
      @if(count($data) > 0)
        @foreach ($data as $user)
          <tr>
            <td>
              <input type="checkbox" name="select-data[]" value="{{$user->id}}">{{$user->name}}</a>
            </td>
            <td>{{$user->email}}</td>
            <td>{{$user->role}}</td>
          </tr> 
        @endforeach  
      @else
        <tr>
          <td colspan="3">No Categories found !!!</td>
        </tr>
      @endif   
    </tbody>
  </table>
  <button>Delete Users</button>
</form>
  • Define the url route that you want to connect on delete request.
  • Add CSRF token.
  • Add the table name.
  • Add the table id.

Sending name and id of the table helps you delete data dynamically.

A checkbox with name select-data[ ] is added to each row so that any number desired data can be selected. A checkbox is added on the table head too which will make all the data selected at once.

Javascript Code

Here's the javascript code that will force all the checkbox get selected on a single click on the checkbox on the table head.

<script>
$('#select-all').click(function(event) {   
  if(this.checked) {
    $(':checkbox').each(function() {
      this.checked = true;                        
    });
  }else{
    $(':checkbox').each(function() {
      this.checked = false;                        
    });
  }
});
</script>

Define Route

Now, define the delete route in your web.php file and create the method in your controller.

Route::post('multipleDelete','adminController@multipleDelete');	

Delete Function

Now, you can add the function as shown below or add your own logic wherever needed.

public function multipleDelete(){
  // store all input data in $data except the values of csrf token
  $data = Input::except('_token');

  // decrypt the tablename and columnname of data id and store in variables  
  $tbl = decrypt($data['tablename']);
  $tblid = decrypt($data['tableid']);        

  // check if the data is empty and return message to the user
  if(empty($data['select-data'])){
    session::flash('message','Please Select the data you want to delete !');
    return redirect()->back();  
  }

  // store all ids sent from the form as array in a variable
  $ids = $data['select-data'];

  // run foreach loop and delete each data one by one
  foreach ($ids as $id){
    DB::table("$tbl")->where("$tblid",$id)->delete();
  }
  
  // display success message to the user
  session::flash('message','Data deleted sucessfully !');
  return redirect()->back();
}

In this way, you can easily create a method to delete any number of data from any table dynamically in Laravel.

Please let everybody know if you have an even better idea to do so.


You must be logged in to answer a question. or