Cover Image for Delete Multiple Records using Checkbox in Laravel
222 views

Delete Multiple Records using Checkbox in Laravel

To delete multiple records using checkboxes in a Laravel application, you’ll typically follow these steps:

  1. Create a Database Table and Model:
    Make sure you have a database table to store the records you want to delete. Create a corresponding model for that table using Laravel Eloquent.
  2. Create a Route:
    Define a route that will handle the deletion of records. In your web.php routes file, you can add a route like this:
PHP
 Route::post('/delete-multiple', 'YourController@deleteMultiple')->name('delete.multiple');
  1. Create a View:
    Create a view that displays the records you want to delete along with checkboxes. For example:
PHP
 <form action="{{ route('delete.multiple') }}" method="POST">
     @csrf
     @foreach($records as $record)
         <label>
             <input type="checkbox" name="selected_records[]" value="{{ $record->id }}">
             {{ $record->name }}
         </label>
     @endforeach
     <button type="submit">Delete Selected</button>
 </form>
  1. Create a Controller Method:
    In your controller, create a method that handles the deletion of multiple records. You can retrieve the selected record IDs from the form input and use the destroy method to delete them:
PHP
 public function deleteMultiple(Request $request)
 {
     $selectedRecords = $request->input('selected_records');

     // Validate the selected record IDs if needed

     YourModel::destroy($selectedRecords);

     return redirect()->back()->with('success', 'Selected records deleted successfully');
 }

Ensure that you’ve imported the necessary classes at the top of your controller file:

PHP
 use Illuminate\Http\Request;
 use App\Models\YourModel; // Replace with your actual model class
  1. Add Flash Messages (Optional):
    You can add flash messages to provide feedback to the user about the status of the deletion operation. In the above example, we used with('success', 'Selected records deleted successfully') to display a success message.
  2. Protect the Route (Optional):
    You can add middleware or authorization checks to protect the delete action based on your application’s requirements. For example, you may want to ensure that only authenticated users with specific permissions can delete records.
  3. Styling and Validation (Optional):
    You can add CSS styles for the checkboxes and implement additional validation or confirmation steps, depending on your application’s needs.

With these steps, you should have a functional mechanism for deleting multiple records using checkboxes in your Laravel application.

YOU MAY ALSO LIKE...

The Tech Thunder

The Tech Thunder

The Tech Thunder


COMMENTS