0

This the data when user submit the form :

POST Data

_token  
"JNDt8WC6kVbvrSdFTKSGnHsfzTuIsbthslf5Gqjs"

invoice_number  
"15"

dateofbill  
"2019-04-19"

customer_name   
"praveen kumar tiwari"

customer_mobile 
"8924001750"

sno 
array:3 [▼
  0 => "1"
  1 => "2"
  2 => "3"
]

item_name   
array:3 [▼
  0 => "jeans"
  1 => "shirt"
  2 => "lower"
]

qty 
array:3 [▼
  0 => "2"
  1 => "3"
  2 => "2"
]

price   
array:3 [▼
  0 => "20000"
  1 => "232"
  2 => "12"
]

gst 
array:3 [▼
  0 => "1200"
  1 => "22"
  2 => "12"
]

discount    
array:3 [▼
  0 => "100"
  1 => "23"
  2 => "12"
]

textarea    
""

i cannot be able to store this data into a table. i am trying with for loop but getting an error "Undefined offset: 3".

Code inside the controller

for($i=0;$i<=count($request['sno']);$i++)
        {
            $invoice = new Invoice;
            $invoice->sendbill_id=$bill->id;
            $invoice->sno=$request['sno'][$i];
            $invoice->item_name=$request->item_name[$i];
            $invoice->qty=$request->qty[$i];
            $invoice->price=$request->price[$i];
            $invoice->gst=$request->gst[$i];
            $invoice->discount=$request->discount[$i];
            $invoice->save();
 }

i want to store these 3 values comming in the array form (sno,item_name,qty,price,gst,discount) in 3 diffrent rows

2 Answers2

1

You should try to use laravel eloquent to save it. Here is some example that you can check it out. Laravel : Many to many insertion

Sok Chanty
  • 1,678
  • 2
  • 12
  • 22
0

The problem you have is indeed your loop: for($i=0;$i<=count($request['sno']);$i++). To be specific it is this right here <=:

$i<=count()
  ^^


Take a look at your array:

[
  0 => "1"
  1 => "2"
  2 => "3"
]

You got a total of 3 objects. count($request['sno']) will therefore return 3 since the count() function does not start counting at 0!
However, calling an index (e.g. $request['sno'][1]) will not return the first object (0 => "1") but the second (1 => "2"). I think you see where I am going.

Since the loop will go on until $i equals 3 the loop will be completed 4 times. At the last time (where $i == 3) you try to get the 4th item out of your array which does not exist so an error message pops up: Undefined offset: 3.

To solve this just change this

$i<=count()
  ^^

to <. The loop will only be executed if $i is still smaller then 3. This is the case if $i == 2. No error message will pop up.

I do not want to attack or hurt you in any way, but it seems to me that you are relatively new to PHP. Of course, that's not a shame, but I'm wondering if a huge framework like Laravel is right for you. First the basics, then comes the advanced.
But that's only as a small comment and tip from me.

Aaron3219
  • 2,168
  • 4
  • 11
  • 28