skip to Main Content

I am trying to delete multiple rows from database.
Everything works fine except last row passed in id array is not deleted.

I am doing it with ajax and below is the link sent

http://local.domain.com/app/deletemultiple/[88,87] 

And here is the code in my api controller

    /**
     * Remove the specified resources from storage.
     *
     * @param  $ids
     * @return JsonResponse
     */
    public function deletemultiple($ids) {
        $idarray = json_decode($ids, TRUE);
        try {
            //$members = Member::whereIn('id', $idarray)->get();
            //return response()->json(array('success' => $members));
            $ids = explode(",", $ids);
            Member::whereIn('id', $ids)->delete();
            return response()->json(array('success' => $ids));
        } catch(Exception $e) {
            return response()->json(array('error' => $e->getMessage()), 400);
        }
    }


//Route is as follows
Route::delete('/app/deletemultiple/{ids}', [MemberController::class, 'deletemultiple'])->name('member.deletemultiple');

No matter how much rows selected and passed. All rows are deleted except the last one in array. If i pass single id as array that is also not deleted.

If I uncomment this code

//$members = Member::whereIn('id', $idarray)->get();
//return response()->json(array('success' => $members));

I get proper response of all ids passed.

Expecting to delete all rows selected.

2

Answers


  1. in your controller you’re decoding json from ids to $idarray but using $ids that’s exploding your json ($ids) string to [1 and 2] you should pass in $idarray to whereIn for delete as this function expects array of ids (in your case).

    Use this in your controller:

    public function deletemultiple($ids) {
        $idarray = json_decode($ids, TRUE);
        try {
            Member::whereIn('id', $idarray)->delete();
            return response()->json(array('success' => $idarray));
        } catch(Exception $e) {
            return response()->json(array('error' => $e->getMessage()), 400);
        }
    }
    
    Login or Signup to reply.
  2. Why not use post method then passed a json array of ids to be deleted. Instead of passing multiple ids in the url path parameter.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search