laravel
  1. laravel-delete-multiple-records-using-checkbox-in-laravel

Delete Multiple Records using Checkbox in Laravel

In this article, we will look at how to delete records using checkbox in Laravel. We will create a form with checkboxes for each record and a delete button, which will delete the selected records when clicked.

Syntax

<input type="checkbox" name="ids[]" value="{{ $record->id }}">
if (isset($request->ids)) {
    Model::whereIn('id', $request->ids)->delete();
}

Example

Suppose we have a table of users, and we want to allow the admin to delete multiple users at once. We will create a table with checkboxes for each user, and a delete button that triggers the delete action.

View

<form method="POST" action="{{ route('delete.multiple') }}">
    @csrf
    <table>
        <thead>
            <tr>
                <th>Select</th>
                <th>Name</th>
                <th>Email</th>
            </tr>
        </thead>
        <tbody>
            @foreach ($users as $user)
            <tr>
                <td><input type="checkbox" name="ids[]" value="{{ $user->id }}"></td>
                <td>{{ $user->name }}</td>
                <td>{{ $user->email }}</td>
            </tr>
            @endforeach
        </tbody>
    </table>
    <input type="submit" value="Delete">
</form>

Controller

public function destroyMultiple(Request $request)
{
    if (isset($request->ids)) {
        User::whereIn('id', $request->ids)->delete();
        return redirect()->back()->with('success', 'Selected users have been deleted successfully!');
    }
    return redirect()->back()->with('error', 'No users were selected to delete!');
}

Output

When the delete button is clicked, the selected users will be deleted from the database, and a success message will be displayed.

Explanation

We have created a form with checkboxes for each record, which will be used to select the records to delete. When the delete button is clicked, we retrieve the selected record IDs from the form and delete them from the database.

Use

This feature can be used in any application where the administrator or authorized users need to delete multiple records at once.

Important Points

  • Make sure to wrap the checkboxes in a form with the method of POST.
  • Use an array for the name attribute of the checkboxes to receive multiple selected values.
  • Use the whereIn method to delete multiple records based on the selected IDs.

Summary

In this article, we have looked at how to delete multiple records using checkbox in Laravel. We have created a form with checkboxes for each record, which is used to select the records to delete. The selected records are deleted from the database when the delete button is clicked. This feature can be used in any application where multiple records need to be deleted at once.

Published on: