【问题标题】:Laravel 6 Form Array $request->input() doesn't workLaravel 6 表单数组 $request->input() 不起作用
【发布时间】:2019-10-09 12:51:15
【问题描述】:

我有这个价格数组,像这样:

<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-&gt;input('prices') 时期望得到一个数组,但这并没有真正发生。也试过$request-&gt;get('prices')

当我$request-&gt;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],
  }), {}));
},

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

【问题讨论】:

    标签: laravel laravel-6


    【解决方案1】:

    嗯,即使您执行 all(),数组似乎也已损坏,因为我在数组中看不到 type 键。

    试试这个:

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

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

    【讨论】:

    • 哦,我的错我把类型涂黑了,我确实得到了类型。但是我已经尝试了json_decode,它给出了与$request-&gt;all()相同的结果
    • @RobinB 在$request-&gt;getContent()$request-&gt;all() 上?
    • 您也可以在将其发布到控制器之前使用JSON.stringify。或者请分享您的 AJAX 代码,以便您获得更好的帮助。
    • $request-&gt;getContent(),我在JS中使用JSON.stringify(),我会用JS更新我的答案
    • 所以你的 JSON 结构是错误的我的朋友。它必须与这部分做一些事情Array.from(formData.entries()).reduce((memo, pair) =&gt; ({ ...memo, [pair[0]]: pair[1], }), {})
    【解决方案2】:

    你需要使用:

    $prices_array = $request->only('prices');
    

    或者:

    $no_prices_array = $request->except('prices');
    

    这样您就可以按字段过滤请求并访问它们。

    【讨论】:

      猜你喜欢
      • 2018-12-23
      • 1970-01-01
      • 2019-01-24
      • 2017-10-08
      • 2020-03-06
      • 2018-11-16
      • 2023-03-27
      • 2018-11-22
      • 2019-02-12
      相关资源
      最近更新 更多