I'm newbie here. I have a problem with my code. I'm trying to insert multiple row to database with laravel
this is my controller code
$references = References::all();
$ref_id = $request->ref_id;
$value = $request->value;
for ($i=1; $i<=count($references); $i ) {
$data_save = [
'ref_id' => $ref_id[$i],
'value' => $value[$i],
];
DB::table('values')->insert($data_save);
}
return redirect('values')->with('success', 'Data created Successfully');
and this is my html code
<form action="{{ url('value/store') }}" method="post" enctype="multipart/form-data">
@csrf
@method('post')
@foreach ($references as $item)
<div >
<div >
<input type="hidden" name="ref_id" value="{{$item->id}}">
<input type="text" value="{{$item->name_ref}}">
</div>
<div >
<input type="number" name="value">
</div>
</div>
@endforeach
<button type="submit" >Save</button>
</form>
and I have an error Uninitialized string offset: 2
is there something wrong with my code?
Thank You.
CodePudding user response:
In your html code, you are passing a string for input ref_id,value
From PHP you are assigning the values of this value to a variable and trying to fetch this as array
<input type="hidden" name="ref_id" value="{{$item->id}}">
<input type="number" name="value">
This needs to be something like this
<input type="hidden" name="ref_id[]" value="{{$item->id}}">
<input type="number" name="value[]" value="1">
The array index will start from 0 so the loop will be like this
for ($i=0; $i<count($references); $i ) {
It is good to do batch insert instead of inserting value inside loop
CodePudding user response:
Use the code from Shibon
<input type="hidden" name="ref_id[]" value="{{$item->id}}">
<input type="number" name="value[]" value="{{$item->value}}">
In your controller
$ref_id = $request->ref_id;
$value = $request->value;
//array start from 0 & count the array for your ref_id not for all reference
for ($i=0; $i<count($ref_id); $i ) {
$data_save = [
'ref_id' => $ref_id[$i],
'value' => $value[$i],
];
DB::table('values')->insert($data_save);
}