guidsen
guidsen

Reputation: 2393

Best approach on single and multiple deletion in laravel

I got a overview page where I can click a button to delete a single row or can selected multiple rows to be deleted.

Because laravel can only delete an item by sending it as a delete request, I am curious what's the best approach on this issue.

I really don't want to use ajax for this because I'm leveraging feedback messages etc with Session::flash.

It would be really great to do something like: item/1?action=destroy for the single row, so I can use a form for the multiple values to be deleted, because I can't nest a form for the single row.

I would love to hear your way of doing these things.

Upvotes: 1

Views: 1080

Answers (2)

Dharmesh Rakholia
Dharmesh Rakholia

Reputation: 1238

public function destroy(Request $request) {

    $sd = $request::get('id');
    if (!empty($sd)) {
        $register = Register::findOrFail($sd);
        $register->delete();
    } else {
        $data = $request::get('chk');

        foreach ($data as $d) {
            $register = Register::findOrFail($d);
            $register->delete();
        }
    }


    return redirect('register');
}

Upvotes: 0

damiani
damiani

Reputation: 7371

Your page can have just a single form, and include submit buttons (or inputs with type="submit") alongside each row, with name="delete" and value set to the ID of the row. In addition, you can have a checkbox next to each row, again with value set to its ID, and then one "Delete Checked Rows" submit button with name="deleteMultiple". This form would POST to a route that would take a look at the Input values, and act accordingly:

  • If a single row's delete button was clicked, Input::get('delete') will contain the ID of the single row to be deleted, which you can pass to your destroy method.

  • If the "Delete Checked Rows" was clicked, Input::has('deleteMultiple') would return true, and the Input would have contain array of which checkboxes were checked. You can then do something like Item::destroy(array(1, 2, 3));.

You can use javascript to streamline or enhance some of the form handling, though it's not necessary.

Upvotes: 1

Related Questions