Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

melx's avatar
Level 4

How to create Multiple Array

Hello i want to create all array base on request, below. I have tried below code and it store array:2 only

My controller

        		if (count($request->pid) > 0) {
        			foreach ($request->pid as $key => $v) {
        				$data2 = ([
        					'projectno' => $fk,
                  'user_id'=>Auth::user()->id,
        					'pid' => $request->pid[$key],
        					'project_date' => $date,
        					'discount' => $request->discount[$key],
        					'qty' => $request->qty[$key],
                  'clientName'=>$request->clientName,
                  'costproject'=>$request->garamakaz,
                  'comment'=>$request->Note,
        					'amountpaid'=>$request->amountpaid,
                  'amount' =>$request->subtotal[$key],
                  'description_expenses' =>$request->descExps[$key],
        					'amount_expenses' =>$request->amountExps[$key]
        				]);

        					$creatdata=Project::create($data2); 

                }


        				}
      if(!$creatdata){
        toastr()->error('Error: Angalia form yako Kama Iko Sawa. Otherwise check Support.');
        return redirect()->back();

      }
      else{
        toastr()->success('Created Successfully');
      return redirect()->back();
      }

          }

My request

array:12 [▼
            "_token" => "aXAkdBEVfO8nLMtxjUoHgxbvBkxMbJz4zIonOvFm"
            "projectdate" => "2021-08-30"
            "clientName" => "Emmanuel"
            "garamakaz" => "600"
            "amountpaid" => "7888"
            "Note" => "madirsha 50"
            "pid" => array:2 [▼
              0 => "1"
              1 => "1"
            ]
            "qty" => array:2 [▼
              0 => "10"
              1 => "10"
            ]
            "discount" => array:2 [▼
              0 => "500"
              1 => "500"
            ]
            "subtotal" => array:2 [▼
              0 => "479500"
              1 => "479500"
            ]
            "descExps" => array:3 [▼
              0 => "Ex1"
              1 => "Ex2"
              2 => "Ex3"
            ]
            "amountExps" => array:3 [▼
              0 => "45666"
              1 => "45666"
              2 => "45666"
            ]
          ]
0 likes
52 replies
Snapey's avatar

Read your question back.... can even YOU understand what you are asking?

melx's avatar
Level 4

I mean how can i store all above arrays, ?, I have tried but it store only array:2

@snapey

Snapey's avatar

organise your form field names better and you would not have these independent arrays

melx's avatar
Level 4

@snapey i have a dynamic rows in my form One project can have many items and many expenses..

melx's avatar
Level 4

this is my form

  <tbody id="tdy">
                      <tr>
                       <td >
                        <select id="mitems" data-subtotal="#subtotal" data-item="#mitems" data-qty="#mqty" class="form-control  totalCalculate" name="pid[]" >
                          <option value=" ">~items~</option>
                          @foreach($items as $key=>$type)
                          <option value="{{$key}}">{{$type}}</option>
                          @endforeach
                        </select>
                      </td>
                      <td ><input type="text" data-subtotal="#subtotal"  required id="mqty" data-item="#mitems" data-qty="#mqty" name="qty[]" class="form-control qty mqty totalCalculate" ></td>
                      <td ><input type="text" name="discount[]" id="mdiscount" required data-qty="#mqty" data-item="#mitems"  data-discount="#mdiscount"    data-subtotal="#subtotal"   class="form-control discountAmount discount  " ></td>
                      <td class="h3"><input type="number" name="subtotal[]" required  class="form-control text-right subtotal" readonly id="subtotal"></td>
                      <td><a href="#" class="btn btn-danger remove"><i class="fa fa-minus-circle"></i></a></td>
                    </tr>
                  </tr>
                </tbody>

<tbody id="tdyExpsn">
                                <tr>
                                <td ><input type="text" name="descExps[]" required="" class="form-control qty" ></td>
                                <td ><input type="text" name="amountExps[]" required="" class="mamount form-control qty" ></td>
                                <td><a href="#" class="btn btn-danger removeExpns"><i class="fa fa-minus-circle"></i></a></td>
                              </tr>
                            </tr>

                          </tbody>
Snapey's avatar

I'm not sure a table can have two tbody sections, but anyway, try it this way

<tbody id="tdy">
    <tr>
        <td>
            <select id="mitems" data-subtotal="#subtotal" data-item="#mitems" data-qty="#mqty"
                class="form-control  totalCalculate" name="item[]pid">
                <option value=" ">~items~</option>
                @foreach($items as $key=>$type)
                <option value="{{$key}}">{{$type}}</option>
                @endforeach
            </select>
        </td>
        <td><input type="text" data-subtotal="#subtotal" required id="mqty" data-item="#mitems" data-qty="#mqty"
                name="item[]qty" class="form-control qty mqty totalCalculate"></td>
        <td><input type="text" name="item[]discount" id="mdiscount" required data-qty="#mqty" data-item="#mitems"
                data-discount="#mdiscount" data-subtotal="#subtotal" class="form-control discountAmount discount  ">
        </td>
        <td class="h3"><input type="number" name="item[]subtotal" required class="form-control text-right subtotal" readonly
                id="subtotal"></td>
        <td><a href="#" class="btn btn-danger remove"><i class="fa fa-minus-circle"></i></a></td>
    </tr>
    </tr>
</tbody>

<tbody id="tdyExpsn">
    <tr>
        <td><input type="text" name="expense[]desc" required="" class="form-control qty"></td>
        <td><input type="text" name="expense[]amount" required="" class="mamount form-control qty"></td>
        <td><a href="#" class="btn btn-danger removeExpns"><i class="fa fa-minus-circle"></i></a></td>
    </tr>
    </tr>

</tbody>

name form array elements as xxxx[]yyyy

where xxxx is the same for all inputs belonging to the same row, and yyyy are the field names of each item in the row

Then you will get a single array that you can iterate over, and you can use .*. in your validation rules, eg item.*.qty can apply a rule to every qty field

melx's avatar
Level 4

And in the controller do i need to use foreach loop?

melx's avatar
Level 4

this is what am getting on dd()

    array:8 [▼
          "_token" => "vwWPNqhPPWvTcHUfOCHWPWIKV9LTmqTvIn4s8Au0"
          "projectdate" => "2021-08-31"
          "clientName" => "nicas"
          "garamakaz" => "60000"
          "amountpaid" => "400000"
          "Note" => "madirsha 50"
          "item" => array:8 [▼
            0 => "1"
            1 => "4"
            2 => "500"
            3 => "191500"
            4 => "2"
            5 => "4"
            6 => "500"
            7 => "191500"
          ]
          "expenses" => array:6 [▼
            0 => "e1"
            1 => "556"
            2 => "e2"
            3 => "556"
            4 => "e3"
            5 => "556"
          ]
        ]

am get this error when am using this code

error

  count(): Parameter must be an array or an object that implements Countable

Controller

 if (count($request->pid) > 0) { //this line has error 

        			foreach ($request->pid as $key => $v) {
        				$data2 = ([
        					'projectno' => $fk,
                  'user_id'=>Auth::user()->id,
        					'pid' => $request->pid[$key],
        					'project_date' => $date,
        					'discount' => $request->discount[$key],
        					'qty' => $request->qty[$key],
                  'clientName'=>$request->clientName,
                  'costproject'=>$request->garamakaz,
                  'comment'=>$request->Note,
        					'amountpaid'=>$request->amountpaid,
                  'amount' =>$request->subtotal[$key],
                  'description_expenses' =>$request->descExps[$key],
        					'amount_expenses' =>$request->amountExps[$key]
        				]);

        					$creatdata=Project::create($data2); //ok wait

                }


        				}

how the controller will be ?

Snapey's avatar

what did you do to my example? You did not implement it correctly?

are you submitting the form with javascript?

melx's avatar
Level 4

no, I just submit normal,,

i changed my form accordingly with your example sir, can you give me what will output after changes the form field name? and how we do on store function

Snapey's avatar

you should have array of item, each has pid, qty, subtotal etc

compare your form field name for each input with my example

melx's avatar
Level 4

do you mean something like this ?

array:8 [▼
              "_token" => "vwWPNqhPPWvTcHUfOCHWPWIKV9LTmqTvIn4s8Au0"
              "projectdate" => "2021-08-31"
              "clientName" => "Emmanuel"
              "garamakaz" => "60000"
              "amountpaid" => "7888"
              "Note" => "madirsha 50"
              "item" => array:4 [▼
                "pid" => "3"
                "qty" => "5"
                "discount" => "500"
                "subtotal" => "129500"
              ]
              "expenses" => array:2 [▼
                "descExps" => "ex3"
                "amountExps" => "4556"
              ]
            ]
Snapey's avatar

yes

better example would be if you had multiple rows

Then you can loop over item and each loop you have access to the fields without having to use numbered indexes

melx's avatar
Level 4

but i just set like this in my form

 name="item[pid]" , name="item[qty]" 

but the problem here, if you dd($request->all()) it takes only one row instead of all rows are entered

i something need to modify here to get all rows

Snapey's avatar

Why don't you just copy the code I sent you?

This item[pid] is NOT going to work

melx's avatar
Level 4

Ok, your code is return this array

                 array:9 [▼
      "_token" => "vwWPNqhPPWvTcHUfOCHWPWIKV9LTmqTvIn4s8Au0"
      "projectdate" => "2021-08-31"
      "clientName" => "Emmanuel"
      "garamakaz" => "60000"
      "amountpaid" => "400000"
      "Note" => "madirsha 50"
   "item" => array:8 [▼
      0 => "1"
      1 => "4"
      2 => "500"
      3 => "191500"
      4 => "2"
      5 => "5"
      6 => "500"
      7 => "239500"
      ]
    
  "expenses" => array:6 [▼
      0 => "ex2"
      1 => "5667"
      2 => "ex3"
      3 => "556"
      4 => "ex1"
      5 => "3455"
      ]
      ] 

as you can see there is no qty, pid, etc..

Snapey's avatar

Show some of your input fields

Check my example. I asked you to write in your input fields;

name="item[]pid"
name="item[]qty"
name="item[]discount"
name="item[]subtotal"

etc

melx's avatar
Level 4
<tr>
                          <td>
                              <select id="mitems" data-subtotal="#subtotal" data-item="#mitems" data-qty="#mqty"
                                  class="form-control  totalCalculate" name="item[]pid">
                                  <option value=" ">~items~</option>
                                  @foreach($items as $key=>$type)
                                  <option value="{{$key}}">{{$type}}</option>
                                  @endforeach
                              </select>
                          </td>
                          <td><input type="text" data-subtotal="#subtotal" required id="mqty" data-item="#mitems" data-qty="#mqty"
                                  name="item[]qty" class="form-control qty mqty totalCalculate"></td>
                          <td><input type="text" name="item[]discount" id="mdiscount" required data-qty="#mqty" data-item="#mitems"
                                  data-discount="#mdiscount" data-subtotal="#subtotal" class="form-control discountAmount discount  ">
                          </td>
                          <td class="h3"><input type="number" name="item[]subtotal" required class="form-control text-right subtotal" readonly
                                  id="subtotal"></td>
                          <td><a href="#" class="btn btn-danger remove"><i class="fa fa-minus-circle"></i></a></td>
                      </tr>

but note that this is dynamic row i have a button which add some rows

Snapey's avatar

You have to edit the template for the dynamic rows in the same way

melx's avatar
Level 4

I did the same but does not return they way you said ,

so how can we store like this request

	                  array:9 [▼
        "_token" => "vwWPNqhPPWvTcHUfOCHWPWIKV9LTmqTvIn4s8Au0"
        "projectdate" => "2021-08-31"
        "clientName" => "Emmanuel"
        "garamakaz" => "60000"
        "amountpaid" => "400000"
        "Note" => "madirsha 50"
        "item" => array:8 [▼
        0 => "1"
        1 => "4"
        2 => "500"
        3 => "191500"
        4 => "2"
        5 => "5"
        6 => "500"
        7 => "239500"
        ]

        "expenses" => array:6 [▼
        0 => "ex2"
        1 => "5667"
        2 => "ex3"
        3 => "556"
        4 => "ex1"
        5 => "3455"
        ]
        ] 
Snapey's avatar

Clearly you cannot. I don't understand why you are not getting the field names coming through....

melx's avatar
Level 4

may i show the full code

tykus's avatar

Fix the name attribute values, e.g. name="item[]subtotal" should be name="item[][subtotal]" :

<input type="number" name="item[][subtotal]" required class="form-control text-right subtotal" readonly
                                  id="subtotal">
Snapey's avatar

Thanks @tykus you may well be right, its a long time since I have needed to do this...

melx's avatar
Level 4

@tykus ,

I have set and this is out put

     array:9 [▼
          "_token" => "vwWPNqhPPWvTcHUfOCHWPWIKV9LTmqTvIn4s8Au0"
          "projectdate" => "2021-08-31"
          "clientName" => "Emmanuel"
          "garamakaz" => "60000"
          "amountpaid" => "400000"
          "Note" => "madirsha 50"
          "item" => array:8 [▼
            0 => array:1 [▼
              "pid" => "1"
            ]
            1 => array:1 [▼
              "qty" => "4"
            ]
            2 => array:1 [▼
              "discount" => "4556"
            ]
            3 => array:1 [▼
              "subtotal" => "187444"
            ]
            4 => array:1 [▼
              "pid" => "3"
            ]
            5 => array:1 [▼
              "qty" => "6"
            ]
            6 => array:1 [▼
              "discount" => "300"
            ]
            7 => array:1 [▼
              "subtotal" => "155700"
            ]
          ]
          "expense" => array:2 [▼
            0 => array:1 [▼
              "descExps" => "E1"
            ]
            1 => array:1 [▼
              "amountExps" => "6788"
            ]
          ]
tykus's avatar

You should put the index number of the loop into the first array brackets in the name attribute value (assuming there is a loop?)

@foreach ($something as $i => $thing)
		<input name="item[{{$i}}][pid]" />
@endforeach

This will group the sets of data for you

Snapey's avatar

Matt Stauffer has it: https://mattstauffer.com/blog/a-little-trick-for-grouping-fields-in-an-html-form/

The rows need a numeric index;

name="item[1]pid"
name="item[1]qty"
name="item[1]discount"
name="item[1]subtotal"

and in your code to insert a new row, it needs to know how many rows there are and then insert the next number.

name="item[2]pid"
name="item[2]qty"
name="item[2]discount"
name="item[2]subtotal"

The second set of braces (@tykus) are not needed

1 like
tykus's avatar

The second set of braces (@tykus) are not needed

Ha! HTML 🤷‍♂️

Snapey's avatar

it puts each of the fields in their own array

tykus's avatar

That's understood @snapey - I had always took it that every key after the initial name required brackets.

tykus's avatar

You have only one row in the table (in your Blade view above); do you need a loop index at all?

melx's avatar
Level 4

I have dynamic row add new row and remove rows,

so i want to know how can i put like let me share all code blade view

    <div class="row">
                <div class="col-md-3">

                </div>
                <!-- /.col -->
                <div class="col-md-9">

                  <div class="box box-primary">

                    <div class="box-header">Project Creation</div>
                   <form method="POST" action="{{route('project.store')}}" enctype="multipart/form-data">
                            {{ csrf_field() }}
                    <div class="box-body">

                      <div class="row">
                           <div class="form-group col-md-3">
                                <label>Tarehe</label>
                                <div class="input-group date">
                                  <div class="input-group-addon">
                                    <i class="fa fa-calendar"></i>
                                  </div>
                                  <input type="date" name="projectdate" class="form-control pull-right" id="datepicker2">
                                </div>
                              </div>
                        <div class="form-group col-xs-3">
                          <label for="name">Mteja:</label>
                          <input type="text" name="clientName"class="form-control" required placeholder="Ingiza Jina La Mteja/project" />

                        </div>
                        <div class="form-group col-xs-3">
                          <label for="name">Garama ya Kazi:</label>
                          <input type="text" name="garamakaz" class="form-control" required placeholder="Ingiza Garama Ya Kazi" />

                        </div>

                        <div class="form-group col-xs-3">
                          <label for="name">Amount Paid:</label>
                          <input type="text" name="amountpaid"class="form-control" required placeholder="Enter Trans cost" />

                        </div>



                      </div>
                    <div class="row">
                      <div class="form-group col-xs-6">
                        <label for="name">Note:</label>
                        <input type="text" name="Note"class="form-control" required placeholder="Aina Ya Kazi" />

                      </div>
                    </div>

                      <br>
                        <h5><strong>List Ya Vifaa</strong>   </h5>
                        <table class="table table-bordered" id="tablerow">
                              <thead>
                                <tr>
                                  <!--    <th class="text-center"> # </th> -->
                                  <th class="text-center"> Item Name </th>
                                  <th class="text-center"> Qty </th>
                                   <th class="text-center"> Discount </th>
                                  <th class="text-center"> Subtotal </th>
                                  <th><a href="#" class="btn btn-info addRow"><i class="fa fa-plus-circle"></i></a></th>
                                </tr>
                              </thead>
                              <tbody id="tdy">
                                    <tr>
                                        <td>
                                            <select id="mitems" data-subtotal="#subtotal" data-item="#mitems" data-qty="#mqty"
                                                class="form-control  totalCalculate" name="item[][pid]">
                                                <option value=" ">~items~</option>
                                                @foreach($items as $key=>$type)
                                                <option value="{{$key}}">{{$type}}</option>
                                                @endforeach
                                            </select>
                                        </td>
                                        <td><input type="text" data-subtotal="#subtotal" required id="mqty" data-item="#mitems" data-qty="#mqty"
                                                name="item[][qty]" class="form-control qty mqty totalCalculate"></td>
                                        <td><input type="text" name="item[][discount]" id="mdiscount" required data-qty="#mqty" data-item="#mitems"
                                                data-discount="#mdiscount" data-subtotal="#subtotal" class="form-control discountAmount discount  ">
                                        </td>
                                        <td class="h3"><input type="number" name="item[][subtotal]" required class="form-control text-right subtotal" readonly
                                                id="subtotal"></td>
                                        <td><a href="#" class="btn btn-danger remove"><i class="fa fa-minus-circle"></i></a></td>
                                    </tr>
                            </tbody>
                          <tfoot>
                              <tr>
                                <td colspan="3" class="h6">Total Amount</td>
                                <td id="mtotalCredit" class="h2 text-right ">0</td>
                              </tr>

                          </tfoot>
                        </table><br>
                        <h5><strong>Matumizi</strong>  </h5>

                                          <table class="table table-bordered">
                                            <thead>
                                              <tr>
                                                <th class="text-center">Maelekezo</th>
                                                <th class="text-center"> Amount</th>
                                                <th><a href="#" class="btn btn-info addRowExpenses"><i class="fa fa-plus-circle"></i></a></th>

                                              </tr>
                                            </thead>
                                            <tbody id="tdyExpsn">
                                              <tr>
                                                  <td><input type="text" name="expenses[][descExps]" required="" class="form-control qty"></td>
                                                  <td><input type="text" name="expenses[][amountExps]" required="" class="mamount form-control qty"></td>
                                                  <td><a href="#" class="btn btn-danger removeExpns"><i class="fa fa-minus-circle"></i></a></td>
                                              </tr>
                                              </tr>

                                          </tbody>
                                        <tfoot>
                                          <tr>

                                            <td colspan="1" class="h6">Total Amount </td>
                                            <td id="totalAmountExps" class="h2 text-right" >0 </td>
                                          </tr>

                                        </tfoot>
                                      </table>
                      </div>
                      <div class="box-footer">
                        <button type="reset" class="btn btn-default pull-left" >Cancel</button>
                        <button type="submit" class="btn btn-info pull-right" >Save</button>
                      </div>
                    </form>

                  </div>
                </div>

              </div>

  <script>
          function addRow()
          {
            var table = document.getElementById("tablerow");
            var tbodyRowCount = table.tBodies[0].rows.length;
            console.log(tbodyRowCount);
            var tr='<tr>'+
            '<td><select name="item[][pid]" data-subtotal="#subtotal'+tbodyRowCount+'" id="mitems'+tbodyRowCount+'" data-item="#mitems'+tbodyRowCount+'" data-qty="#mqty'+tbodyRowCount+'" class="form-control totalCalculate">'+
            '<option value=" ">~items~</option>'+
            '@foreach($items as $key=>$type)'+
            '<option value="{{$key}}">{{$type}}</option>'+
            '@endforeach'+
            '</select>'+
            '</td>'+
            '<td><input type="text" name="item[][qty]"  data-subtotal="#subtotal'+tbodyRowCount+'" id="mqty'+tbodyRowCount+'" data-item="#mitems'+tbodyRowCount+'" data-qty="#mqty'+tbodyRowCount+'" class="form-control totalCalculate qty " required=""></td>'+
               '<td><input type="text" name="item[][discount]" id="mdiscount'+tbodyRowCount+'" data-qty="#mqty'+tbodyRowCount+'" data-item="#mitems'+tbodyRowCount+'" data-discount="#mdiscount'+tbodyRowCount+'"  data-subtotal="#subtotal'+tbodyRowCount+'"   class="form-control discountAmount discount  " ></td>'+
            '<td class=" h3"><input type="number" name="item[][subtotal]" class="subtotal form-control text-right " id="subtotal'+tbodyRowCount+'" readonly></td>'+
            '<td><a href="#" class="btn btn-danger remove"><i class="fa fa-minus-circle"></i></a></td>'+
            '</tr>';
            $('#tdy').append(tr);
          };

            function addRowExpenses()
                  {
                  var tr='<tr>'+
              '<td ><input type="text" name="expenses[]descExps" required class="form-control desc" ></td>'+
              '<td><input type="text" name="expenses[]amountExps" required class="form-control amount mamount" required=""></td>'+
              '<td><a href="#" class="btn btn-danger remove"><i class="fa fa-minus-circle"></i></a></td>'+
              '</tr>';
              $('#tdyExpsn').append(tr);
            };
tykus's avatar

You get the number of rows currently in the table here:

var tbodyRowCount = table.tBodies[0].rows.length;

That should be the index whenever you add a new row assuming that the existing row(s) already have an 0-based index series 0, 1,...

 var tr='<tr>'+
            '<td><select name="item[' + tbodyRowCount + '][pid]" data-subtotal="#subtotal'+tbodyRowCount+'" id="mitems'+tbodyRowCount+'" data-item="#mitems'+tbodyRowCount+'" data-qty="#mqty'+tbodyRowCount+'" class="form-control totalCalculate">'+
1 like
melx's avatar
Level 4

@tykus ok, and how can i loop? Because i have two group array...

Item and expenses

Foreach($item as $key=>value){
       "pid"=>$request=>pid[key]
  }
tykus's avatar

how can i loop?

Do you mean in PHP; what data are you working with in the view?

melx's avatar
Level 4

I mean in cotroller

How function look like?

melx's avatar
Level 4

@tykus am asking because am getting this error

       Trying to access array offset on value of type null

see my controller

        			foreach ($request->item as $key => $v) {
        				$data2 = ([
        					'projectno' => $fk,
                  'user_id'=>Auth::user()->id,
        					'pid' => $request->pid[$key],
        					'project_date' => $date,
        					'discount' => $request->discount[$key],
        					'qty' => $request->qty[$key],
                  'clientName'=>$request->clientName,
                  'costproject'=>$request->garamakaz,
                  'comment'=>$request->Note,
        					'amountpaid'=>$request->amountpaid,
                  'amount' =>$request->subtotal[$key],
                  'description_expenses' =>$request->descExps[$key],
        					'amount_expenses' =>$request->amountExps[$key]
        				]);

        					$creatdata=Project::create($data2);


        				}
tykus's avatar

You are iterating over $request->input('items'), to the index is $keyand the value is an associative array keyed withpid, discount` etc.

foreach ($request->item as $key => $v) {
    $data2 = [
        'projectno' => $fk,
        'user_id'=>Auth::user()->id,
        'pid' => $v['pid'],
        'discount' => $v['discount'],
//      etc
melx's avatar
Level 4

error

           Array to string conversion

Code

       	foreach ($request->item as $key => $v) {
        				$data2 = [
        					'projectno' => $fk,
                  'user_id'=>Auth::user()->id,
        					'pid' => $request->$v['pid'],
        					'project_date' => $date,
        					'discount' => $request->$v['discount'],
        					'qty' => $request->$v['qty'],
                  'clientName'=>$request->clientName,
                  'costproject'=>$request->garamakaz,
                  'comment'=>$request->Note,
        					'amountpaid'=>$request->amountpaid,
                  'amount' =>$request->$v['subtotal'],
                  'description_expenses' =>$request->$v['descExps'],
        					'amount_expenses' =>$request->$v['amountExps']
        				];

        					$creatdata=Project::create($data2);


        				}
tykus's avatar

What’s this 'pid' => $request->$v['pid'],? That’s not what I described earlier

melx's avatar
Level 4

Ok sorry, forget that,, but i changed and get this error

  Undefined index: descExps

and this is found in the second array "expenses" instead of "item"

tykus's avatar

How does the second element in expenses related to any item?

melx's avatar
Level 4

it just show the expenses of that projectNumber so i just insert in one table, or do you any advice

my idea is:: I have a project which uses many item(products), and in that project i want also to record the expenses. so that i have one form which has items and expenses

tykus's avatar

So each item has multiple expenses (and these expenses are duplicated across each item in the array of items)???

melx's avatar
Level 4

no, each project has multiple items and expenses

tykus's avatar

So, the first item should match with the first expense? So, you would use the $key to index into $request->input('expenses', [])

$expenses = $request->input('expenses', []);
foreach ($request->item as $key => $item) {
    $data2 = [
        'projectno' => $fk,
        'user_id'=>Auth::user()->id,
        'pid' => $item['pid'],
        'project_date' => $date,
        'discount' => $item['discount'],
        'qty' => $item['qty'],
        'clientName'=>$request->clientName,
        'costproject'=>$request->garamakaz,
        'comment'=>$request->Note,
        'amountpaid'=>$request->amountpaid,
        'amount' =>$item['subtotal'],
        'description_expenses' => $expenses[$key]['descExps'] ?? null,
        'amount_expenses' =>$expenses[$key]['amountExps'] ?? null,
];

$creatdata=Project::create($data2);
1 like
melx's avatar
Level 4

@tykus , i tried the code but the issue is, if You have 2 rows items and 3 rows expenses

It create that 2 rows of items and two rows of expenses. One row of expenses is missing,,

tykus's avatar

How should that scenario be handled??? I don’t know your business rules; I can only work with the information you provide.

hiddon2's avatar

To do this, you need to keep track of three things: (1) how many arrays you've already created (so you can stop at 30); (2) what length of array you're on (so you can create the next array with the right length); and (3) what integer-value you're up to (so you can populate the next array with the right values). Here's one way:

private Set<int[]> createArrays() {
    final Set<int[]> arrays = new HashSet<int[]>();
    int arrayLength = 3;
    int value = 1;
    for (int arrayNum = 0; arrayNum < 30; ++arrayNum) {
        final int[] array = new int[arrayLength];
        for (int j = 0; j < array.length; ++j) {
            array[j] = value;
            ++value;
        }
        arrays.add(array);
        arrayLength += 3;
    }
    return arrays;
}

Please or to participate in this conversation.