Laravel通过关联数组循环然后保存到数据库

时间:2018-12-12 00:40:07

标签: php arrays json laravel

我是一个初学者,目前正在学习Vue js和Laravel。因此,我试图弄清楚如何通过axios创建单个POST请求,然后将多个条目插入数据库。

我有这个数组,例如:

{
  "comakers": [
    {
      "name": "Sample",
      "email": "sample@email.com"
    },
    {
      "name": "Test",
      "email": "test@email.com"
    }
  ]
}

然后在我的laravel控制器上,我想像这样做一个foreach循环

public function update(Request $request, $id)
{
    $data = $request->all();

    foreach ($data as $comaker){
        $nominate = new Nominate();
        $nominate->loan_application_id = $id;
        $nominate->comaker_name = $comaker->name;
        $nominate->comaker_email = $comaker->email;

        $nominate->save();
    }

}

但是出现错误“试图获取非对象的属性'名称'” 。有人可以给我一些有关如何实现这一点的想法吗?

顺便说一句,我正在尝试使用控制器的更新功能。基本上,我想(如果不存在则插入新的)或(当存在现有数据时进行编辑)。我在这里使用正确的方法吗?

(更新)

当我尝试获取$data = $request->all();的值时,

laravel dd或dump显示此内容

array:1 [
  "comakers" => array:2 [
    0 => array:2 [
      "name" => "Sample"
      "email" => "sample@email.com"
    ]
    1 => array:2 [
      "name" => "Test"
      "email" => "test@email.com"
    ]
  ]
]

3 个答案:

答案 0 :(得分:1)

我不认为all()将返回一个对象数组,而是一个关联数组。因此,您可以尝试以下操作:

// Notice that you should use `json()` since the data is in json format
$data = $request->json()->all();

foreach ($data['comakers'] as $comaker) {
  $nominate = new Nominate();
  $nominate->loan_application_id = $id;
  $nominate->comaker_name = $comaker['name'];
  $nominate->comaker_email = $comaker['email'];

  $nominate->save();
}

当然,您也可以将结果投射到这样的对象上:

foreach ($data['comakers'] as $item) {
  $comaker = (object) $item;
  $nominate = new Nominatevar_dump($data);
  ...

我还建议您仅打印出结果的内容,以查看其实际包含的内容,例如使用var_dump()

var_dump($data);

答案 1 :(得分:1)

我认为您是在Json变量上进行前向操作,而不是其中的comakers对象。

foreach ($data->comakers as $comaker) {
        $nominate = new Nominate();
        $nominate->loan_application_id = $id;
        $nominate->comaker_name = $comaker->name;
        $nominate->comaker_email = $comaker->email;

        $nominate->save();
}

答案 2 :(得分:1)

尝试循环时,您忘记了comaker键,您应该这样做

$data = $request->all();

foreach ($data['comakers'] as $comaker){
    $nominate = new Nominate();
    $nominate->loan_application_id = $id;
    $nominate->comaker_name = $comaker['name'];
    $nominate->comaker_email = $comaker['email'];

    $nominate->save();
}