Dora
Dora

Reputation: 6970

How to pass an array to PHP using $http.delete with AngularJS and Laravel?

In my AngularJS Service I have an array of id's which I want to pass to a PHP server so it can delete them but somehow I keep on getting a 500/Internal Server Error response.

In my server log it's saying that the request is missing one argument which means the passing to the server wasn'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}
  });
}

For my php controller I have this:

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 I wanted to double check that it's being passed successfully before I do anything else.

Can someone tell me what's going wrong here?

Upvotes: 0

Views: 235

Answers (1)

Georges O.
Georges O.

Reputation: 992

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());
}

Upvotes: 1

Related Questions