Laravel arrays and foreach



因此,我通过POST请求从Ionic应用程序向API发送一系列调味品,这些调味品在移动部件上以复选框表示。我想得到选中的复选框,这样我就可以相应地创建表行。

路由触发时调用的方法有以下部分:

$condiments = Input::only('condiments');
foreach ($condiments as $condiment) {
        if ($condiment['checked'] == 1) {
            OrderCondiment::create(['order_item_id' => $orderItem, 
                                    'condiment_id' => $condiment->id]);
        }
}

但是我得到了Illegal string offset 'checked'错误。我尝试使用$condiment->checked,但后来出现Trying to get the property of non-object错误。。。我错过了什么。。。除了咖啡

编辑

dd($condiments)
array:1 [
  "condiments" => "[{"id":1,"name":"ut","price":3,"created_at":null,"updated_at":null,"checked":1},{"id":2,"name":"ipsam","price":5,"created_at":null,"updated_at":null,"checked":1},{"id":3,"name":"dolores","price":10,"created_at":null,"updated_at":null,"checked":1},{"id":4,"name":"esse","price":3,"created_at":null,"updated_at":null,"checked":0},{"id":5,"name":"aliquid","price":1,"created_at":null,"updated_at":null,"checked":0},{"id":6,"name":"sunt","price":3,"created_at":null,"updated_at":null,"checked":0},{"id":7,"name":"saepe","price":1,"created_at":null,"updated_at":null,"checked":0},{"id":8,"name":"impedit","price":10,"created_at":null,"updated_at":null,"checked":0},{"id":9,"name":"dolores","price":4,"created_at":null,"updated_at":null,"checked":0},{"id":10,"name":"veniam","price":2,"created_at":null,"updated_at":null,"checked":0}]"
]

将字符串转换为数组

$condiments = Input::only('condiments');
$condiments= json_decode( $condiments['condiments']) ;
foreach ($condiments as $condiment) {
    if ($condiment->checked == 1) {
        OrderCondiment::create(['order_item_id' => $orderItem, 
                                'condiment_id' => $condiment->id]);
    }
}

最新更新