AbhimanuSharma
AbhimanuSharma

Reputation: 453

Axios is sending array instead of json object in post request

I am trying to send a post request using axios from Vuejs front-end to Laravel in backend.

const data = {
            file: {id}
        }

        axios.post('api/documents/remove', data).then((response) => {
                console.log(response.data);
            }
        }).catch(err => { console.log(err.response.data); })

In laravel, I am printing the request like this,

 public function removeFile(Request $request)
 { 
    dd($request);
 }

This is my output.

Illuminate\Http\Request {#51
  #json: Symfony\Component\HttpFoundation\ParameterBag {#43
  #parameters: array:8 [
  "file" => array:1 [
    "id" => 61
  ]
}

Upvotes: 0

Views: 781

Answers (3)

saifulmasud
saifulmasud

Reputation: 7

Request $request is delivering array not object instance, so, you can access only like the followings:

$request->input('file')['id']

Or

$request->file['id']

Or

$request->input('file.id')

Or, only file field

$request-all()[0]['file']['id']

Upvotes: 0

T.J. Crowder
T.J. Crowder

Reputation: 1075417

PHP's "arrays" aren't really arrays, they're ordered maps. That's what your output is showing, that the request contains paramters, which is an ordered map, and the file parameter is an ordered map with id => 61 in it. In JavaScript that would be an object (or Map, sometimes); in many other languages it would be some kind of map or dictionary. PHP calls them arrays.

Either way, if you access the file parameter (I don't "do" Laravel so I don't know how you do that), you can get the id from it like this: $file[id]. Looking at the Laravel docs, it looks like that would be:

$file = $request->input('file');
$id = $file['id'];

Upvotes: 2

Donkarnash
Donkarnash

Reputation: 12845

You can get the data of $request as

$file = $request->input('file');
$file['id'];

//Or

$fileId = $request->input('file.id');

Upvotes: 0

Related Questions