1
votes

I have a dynamic form that successfully adds multiple rows by clicking on the add button. the problem is when I try to save data into the database it throws the below error.

{message: "Illegal string offset 'supplier_id'", exception: "ErrorException",…} exception: "ErrorException" file: "C:\xampp\htdocs\Bookstore\app\Http\Controllers\API\PurchaseController.php" line: 87 message: "Illegal string offset 'supplier_id'" trace: [{file: "C:\xampp\htdocs\Bookstore\app\Http\Controllers\API\PurchaseController.php", line: 87,…},…]

and help will be highly appreciated

Code in the controller

 public function store(Request $request)
    {

$products = json_decode($request->getContent('myArray') , true);

    foreach( $products as $product )
    {
        Purchase::create([
            'supplier_id' => $product['supplier_id'],
            'date' => $product['date'],
            'totalAmount' => $product['totalAmount'],
            'description' => $product['description']

        ]);
    }

        //   return dd($myArray);
       return response()->json($Purchase);            


    }

Form in the Purchases Vue

   <form
            @submit.prevent="
                            editMode ? updatePurchase() : createPurchase()
                        "
          >
            <div class="modal-body">
              <div class="form-horizontal">
                <tr v-for="(invoice_product, k) in invoice_products" :key="k">

                  <td scope="row" class="trashIconContainer">
                    <i class="fa fa-trash" @click="deleteRow(k, invoice_product)"></i>
                  </td>
                  <td style="width: 20%;">

                    <select
                      name="supplier_id[]"
                      id="supplier_id"
                      :class="{
                                        'is-invalid': form.errors.has(
                                            'supplier_id'
                                        )
                                    }"
                      class="form-control"
                      v-model="invoice_product.supplier_id"
                      data-live-search="true"
                    >
                      <option value selected>د پلورونکي ټاکنه</option>
                      <option
                        v-for="Supplier in Suppliers"
                        :key="Supplier.id"
                        :value="Supplier.id"
                      >{{ Supplier.name }}</option>
                    </select>
                    <has-error :form="form" field="supplier_id"></has-error>
                  </td>
                  <td style="width: 20%;padding-right: 10px;">
                    <input
                      dir="rtl"
                      id="text1"
                      v-model="invoice_product.date"
                      placeholder="نیټه "
                      type="date"
                      name="date[]"
                      class="form-control"
                      :class="{
                                        'is-invalid': form.errors.has('date')
                                    }"
                    />
                    <has-error :form="form" field="date"></has-error>
                  </td>
                  <td style="width: 20%;padding-right: 10px;">
                    <input
                      dir="rtl"
                      id="text1"
                      v-model="invoice_product.totalAmount"
                      placeholder="  ټولی پیسی "
                      type="number"
                      name="totalAmount[]"
                      class="form-control"
                      :class="{
                                        'is-invalid': form.errors.has(
                                            'totalAmount'
                                        )
                                    }"
                    />
                    <has-error :form="form" field="totalAmount"></has-error>
                  </td>
                  <td style="width: 40%;padding-right: 10px;">
                    <textarea
                      v-model="invoice_product.description"
                      placeholder="تشریح"
                      type="text"
                      name="description[]"
                      class="form-control"
                      :class="{
                                        'is-invalid': form.errors.has(
                                            'description'
                                        )
                                    }"
                    ></textarea>

                    <has-error :form="form" field="description"></has-error>
                  </td>
                </tr>
                <button type="button" class="btn btn-info" @click="addNewRow">
                  <i class="fa fa-plus-circle"></i>
                  Add
                </button>
              </div>
              <div class="modal-footer">
                <button type="button" class="btn btn-danger" data-dismiss="modal">لغوه کړی</button>

                <button
                  v-show="editMode"
                  :disabled="form.busy"
                  type="submit"
                  class="btn btn-success"
                >تازه کړی</button>
                <button
                  v-show="!editMode"
                  :disabled="form.busy"
                  type="submit"
                  class="btn btn-primary"
                >خوندی کړی</button>
              </div>
            </div>
          </form>

Sript in the Purchases Vue

 data() {
    return {
      invoice_products: [
        {
          supplier_id: "",
          totalAmount: "",
          date: "",
          description: ""
        }
      ],
}
 deleteRow(index, invoice_product) {
      var idx = this.invoice_products.indexOf(invoice_product);
      console.log(idx, index);
      if (idx > -1) {
        this.invoice_products.splice(idx, 1);
      }
      this.calculateTotal();
    },
    addNewRow() {
      this.invoice_products.push({
        supplier_id1: "",
        totalAmount1: "",
        date1: "",
        description1: ""
      });
    },
 createPurchase() {

      axios
        .post("api/Purchase", {
          myArray: this.invoice_products
        })
        .then(() => {
          $("#addNew").modal("hide");
          toast.fire({
            icon: "success",
            html: "<h5> معلومات په بریالیتوب سره خوندي شول</h5>"
          });
          Fire.$emit("refreshPage");
          this.form.reset();
        })
        .catch(er => {
          console.log(er);
        });

    },
1
The exception is already telling you what the problem is... have you dumped the products variable in the controller to see what are you receiving? That's a good starting point to debug this.César Escudero
Well, there you have. You can't access a null value as if it was an array, right? that's why it's telling you that you're trying to access an illegal offset in the exception. The next you might want to do is dump your request object to see what you're getting there. I think from that point you should be able to solve this by yourself.César Escudero
Sorry in dd() I ge the data array:1 [ "myArray" => array:2 [ 0 => array:4 [ "supplier_id" => 2 "totalAmount" => "7" "date" => "2020-04-07" "description" => "hh" ] 1 => array:8 [ "supplier_id1" => "" "totalAmount1" => "" "date1" => "" "description1" => "" "supplier_id" => 3 "date" => "2020-04-14" "totalAmount" => "8" "description" => "hhh" ] ] ]Basharmal

1 Answers

1
votes

I found the solution

public function store(Request $request)
    {

  if ($purchases= $request->get('myArray')) {
    foreach($purchases as $purchase) {
      Purchase::create([
            'supplier_id' => $purchase['supplier_id'],
            'date' => $purchase['date'],
            'totalAmount' => $purchase['totalAmount'],
            'description' => $purchase['description']

        ]);
    }
  }

       return response()->json();            


    }