Reputation: 2462
I need to insert array data in to table. My table structure and form structure are given below. Please check and help me to insert data. Getting an error in browser
table
id form_field_id(foreign key) value create_at updated_at
1 14 test1 2016-02-23 2016-02-23
2 15 test2 2016-02-23 2016-02-23
3 16 test3 2016-02-23 2016-02-23
Form
<input type="text" class="form-control" name="field[]" id="field1">
<input type="hidden" id="one" value="{{ $formField->id }}" name="fieldID[]">
<input type="text" class="form-control" name="field[]" id="field2">
<input type="hidden" id="two" value="{{ $formField->id }}" name="fieldID[]">
<input type="text" class="form-control" name="field[]" id="field3">
<input type="hidden" id="three" value="{{ $formField->id }}" name="fieldID[]">
Laravel code
$formValue = new Formvalue;
$formValue->form_field_id = $request->fieldID;
$formValue->value = $request->field;
$formValue->save();
When I print dd($request->fieldID);
and dd($request->field);
Result of field ID
array:3 [▼
0 => "14"
1 => "15"
2 => "16"
]
Result of field
array:3 [▼
0 => "asd"
1 => "asdasdasda"
2 => "on"
]
Error
Argument 1 passed to Illuminate\Database\Grammar::parameterize() must be of the type array, string given, called in C:\xampp\htdocs\laravel\vendor\laravel\framework\src\Illuminate\Database\Query\Grammars\Grammar.php on line 678 and defined
Model
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Formvalue extends Model
{
protected $guarded = ['id'];
protected $table = 'form_values';
public function formValues()
{
return $this->belongsTo('App\Formfield');
}
}
Upvotes: 1
Views: 3112
Reputation: 2462
I have applied below code and working perfectly now.
foreach($request->fieldID as $values){
$fieldsIdResult[] = $values;
}
foreach($request->field as $keys){
$fieldsValueResult[] = $keys;
}
$j = 0;
while($j < count($request->fieldID)) {
$IdResult = $fieldsIdResult[$j];
$ValResult = $fieldsValueResult[$j];
$formValue = new Formvalue;
$formValue->form_field_id = $IdResult;
$formValue->value = $ValResult;
$formValue->save();
$j++;
}
Upvotes: 1
Reputation: 764
You should insert your data inside loop try this
foreach($request->all() as $value){
$formValue = new Formvalue;
$formValue->form_field_id = $value->fieldID;
$formValue->value = $value->field;
$formValue->save();
}
in your model add fillable values
protected $fillable = ['form_field_id','value'];
Upvotes: 0