问题
I have multiple input fields with same name in a page when i try to save i throws an error.how should i save data from multiple table row data into database. the error Creating default object from empty value at here $varientaccesss->variant_id = $request->input('varient'),
Controller
public function storevarient_update(Request $request)
{
//return $request;
$varientprice = new Price();
$varientprice->variant_id = $request->input('varient');
$varientprice->discount = $request->input('discount');
$varientprice->price = $request->input('vehicleprice');
$varientprice->save();
$varientaccess = new Categoryvariantmapping();
foreach ($varientaccess as $varientaccesss){
$varientaccesss->variant_id = $request->input('varient');
$varientaccesss->cat_id = $request->input('test');
$varientaccesss->rate = $request->input('cat_price');
$varientaccesss->status = '0';
$varientaccess->save();
}
return redirect('Varientupdate')->with('success', 'Details Added Successfully');
}
dd($request->all);
回答1:
you can save like this
public function storevarient_update(Request $request)
{
//return $request;
$varientprice = new Price();
$varientprice->variant_id = $request->input('varient');
$varientprice->discount = $request->input('discount');
$varientprice->price = $request->input('vehicleprice');
$varientprice->save();
$cat_id = $request->input('cat_price');
$test_ids = $request->input('test');
foreach($test_ids as $key => $test)
{
$varientaccesss = new Categoryvariantmapping();
$varientaccesss = new Categoryvariantmapping();
$varientaccesss->variant_id = $request->input('varient'),
$varientaccesss->cat_id = $test,
$varientaccesss->rate = $cat_id[$key],
$varientaccesss->status = '0',
$varientaccess->save();
}
return redirect('Varientupdate')->with('success', 'Details Added Successfully');
}
回答2:
The purpose of this is to initialize a new data which you are going to save in the database soon
$varientaccess = new Categoryvariantmapping();
but you put it outside the loop
$varientaccess = new Categoryvariantmapping();
foreach(....)
which mean no matter how many rows inside foreach it will only save once because you it won't initialize again
so the solution is to put it inside loop
foreach(....) {
$varientaccess = new Categoryvariantmapping();
$varientaccesss->variant_id = $request->input('varient');
$varientaccesss->cat_id = $request->input('test');
$varientaccesss->rate = $request->input('cat_price');
$varientaccesss->status = '0';
$varientaccess->save();
}
来源:https://stackoverflow.com/questions/52514076/save-data-from-table-rows-in-laravel