首页 > 解决方案 > 在 laravel 5.8 的 foreach 循环中存储数据

问题描述

我在存储数据方面需要您的帮助。

我有几个产品的购物车,现在我想Order通过单击提交按钮将所有这些产品同时存储在表中

我的观点blade.php

此视图显示购物车中的所有产品,我需要将这些信息存储在Order表中

<form action="{{route('order.store')}}" method="post">
  @csrf
  @foreach ($cart as $ct)

  <input type="text" name="product_id" value="{{$ct->id}}" hidden>

  <input type="text" value="{{$ct->color}}" name="color" >

  <input type="text" value="{{$ct->size}}" name="size" >

  <input type="text" value="{{$ct->price}}" name="price" >

  @endforeach
 <button type="submit">submit</button>            
</form>

在我的Order表格中,我需要填写这 4 列:product_id、color、size 和 price。

我的 foreach 循环从Cart表中获取数据,并且所有数据都显示没有错误。

我的问题是,我如何Order只需单击一次提交按钮就可以将这些数据存储到我的表中?我应该在我store function的 in 中写什么OrderController

如果我的购物车有 3 件产品,那么我的期望值是Order表格,如下所示:

id----product_id----size----color---price---+
---------------------------------------------
1      1             abc     xyz     123
---------------------------------------------
2      2             abc2    xyz2    456
---------------------------------------------
3      3             aaa     bbb     789

感谢您的帮助!

标签: phpmysqllaravel-5.8

解决方案


D B:

Order:
    user_id
    created_at
    ...


orderProducts:
    price
    color
    size
    order_id (relation)
    product_id (relation)
    ...

看法

<form action="{{route('order.store')}}" method="post">
  @csrf
  @foreach ($cart as $ct)

  <input type="text" name="products[]" value="{{$ct->product_id}}" hidden>

  <input type="text" value="{{$ct->color}}" name="color[]"  >

  <input type="text" value="{{$ct->size}}" name="size[]" >

  <input type="text" value="{{$ct->price}}" name="price[]" >

  @endforeach
 <button type="submit">submit</button>            
</form>

控制器功能存储

        $order= new Order;// change the model here
        // .. complete your information's like user id or created_at 
        $order->save();

        foreach($request->products as $key=>$product_id)
        {
            $product = Product::findOrFail($product_id); // validations the product id 

            // get your information's from db (color,size,price) don't trust get information's from user .
            // $product->price , $product->color .... or get from cart 
           //from cart direct $color[$key] or $price[$key] or $size[$key]  "I don't recomend to use this point"


            // must be create new table
            $orderProducts=new orderProducts; // create new table ordersProducts

            $orderProducts->price = $product->price;
            // .. complete your information's

            $orderProducts->order_id = $order->id; // primary key
            $orderProducts->product_id= $product->id;

            $orderProducts->save();

        }

注意: - 如果在“findOrFail”步骤中失败,您需要使用 try-catch 记录信息,或者更改为查找,然后如果在表中未找到产品,则记录订单未完成并向用户显示错误


推荐阅读