首页 > 解决方案 > Laravel 6 表单数组 $request->input() 不起作用

问题描述

我有一系列价格,如下所示:

<input type="input" id="prices[type][1]" name="prices[type][1]">
<input type="input" id="prices[type][2]" name="prices[type][2]">

我通过发布请求(JSON:是的,Content-Type设置为application/json)发送此数据,并希望在我使用时获得一个数组,$request->input('prices')但这并没有真正发生。也试过了$request->get('prices')

当我这样做时,$request->all()我确实得到了我提交的所有数据:

不同请求方法的转储

JS 用来发出请求:

const response = await fetch(this.action, {
  method: 'POST',
  credentials: 'same-origin',
  headers: {
    'Content-Type': 'application/json',
    'X-CSRF-TOKEN': this.$page.token,
  },
  body: this.formData(),
});

const body = await response.json();

this.formData()

formData(): Object {
  const formData = new FormData(this.$el);

  return JSON.stringify(Array.from(formData.entries()).reduce((memo, pair) => ({
    ...memo,
    [pair[0]]: pair[1],
  }), {}));
},

有没有人知道哪里可能出错?

标签: laravellaravel-6

解决方案


嗯,即使您这样做,看起来数组也已损坏,all()因为我没有看到type数组中的键。

试试这个:

dd(json_decode($request->getContent(), true));

由于它是 JSON,因此您需要获取正文并将其转换为数组。


推荐阅读