Dora Dora - 1 month ago 6
AngularJS Question

how to passing array to backend using $http.delete using angluar and laravel?

In my service I got an array of ids which I want to pass it to the backend so the backend can delete the specific ids but somehow I keep on getting 500 (Internal server error). I checked my log it's saying missing one argument which means the passing to the backend isn't successful.

I have something like this in my service.

destroySelected : function (ids) {
// console.log(ids);
// return $http.delete('/posts/destroySelected', ids);
return $http({
method: 'DELETE',
url: '/posts/destroySelected/',
headers: {'Content-Type': 'application/json;charset=utf-8'},
data: {ids : ids}
});
}


I am confident that the
ids
is either empty array or there's something in the array. For my php controller I have

public function destroySelected($ids) {
echo "<pre>" . var_export($ids, true) . "<pre>";
die;
return response()->json(Post::get());
}


my route

Route::delete('posts/destroySelected/', 'PostController@destroySelected');


it's empty but wanted to double check it's being passed successfully before I do anything else but guess I failed.

Can someone give me an idea? Thanks a lot

Answer

You didn't provided any data to the controller :)

You have : url: '/posts/destroySelected/' and data: {ids : ids}

So, your final url will be /posts/destroySelected/?ids=1 (for example)

The parameter $ids on your request require an url route parameter (for example route /posts/destroySelected/{ids}) and not a query parameter (_GET/_POST)

Solution:

        return $http({
            method: 'DELETE',
            url: '/posts/destroySelected/' + ids,
            headers: {'Content-Type': 'application/json;charset=utf-8'}
        });

To get the query parameter (_GET), you can use:

<?php
public function destroySelected(Request $request) {
    $ids = $request->input('ids'); // will get the value of $_REQUEST['ids'] ($_GET or $_POST)
    // var_dump($request->all()); for all values

    echo "<pre>" . var_export($ids, true) . "<pre>";
    die;
    return response()->json(Post::get());
}