I'm trying to insert array to DB ( double rows with the same FK (product_id) ) , which i have parent table(Products) and child table(Product_translation) . I have 2 Model with relationship and getting the lastinserted Id of the product table , but the issue with me now is it's save word(array) to DB , instead of loop on this array to insert it correclty using laravel form : and here's my form
{!!Form::text('title[]'," ",["class"=>"form-control col-md-7 col-xs-12" )!!}
{!!Form::text('language[]'," ",["class"=>"form-control col-md-7 col-xs-12" ])!!}
{!!Form::text('title[]'," ",["class"=>"form-control col-md-7 col-xs-12" )!!}
{!!Form::text('language[]'," ",["class"=>"form-control col-md-7 col-xs-12" )!!}
and the controller function here's :
function store( ){
$parentproduct = new Product();
$parentproduct->id = Input::get('id');
$parentproduct->save();
$insertedId = $parentproduct->id;
$langArray = Input::get('language');
$titleArray = Input::get('title');
$count = count($titleArray);
for($i = 0; $i < $count; $i++)
{
$product = new ProductsTranslation(array('language' => $langArray[$i], 'title' => $titleArray[$i],
$product->product_id = $insertedId));
$product->save();
}
DB::table('products_translations')->insert($product);
}
But I'm getting this error:
Creating default object from empty value
Which is referring to that line :
$product->product_id = $insertedId
Updated now i have a problem to store the array to my database :
My form getting me this array :
array:2 [▼
0 => array:4 [▼
"id" => null
"product_id" => 225
"title" => "English Title"
"language" => "En"
]
1 => array:4 [▼
"id" => null
"product_id" => 225
"title" => "Arabic title"
"language" => "Ar"
]
]
And i need to save this to database but it didn't !
which i'm using this code at the controller :
function store(Request $request) {
$parentproduct = new Product();
$parentproduct->id = Input::get('id');
$parentproduct->save();
$insertedId = $parentproduct->id;
foreach ($request->input('language') as $i=>$language) {
$insertprod[] = array(
'id' =>$request->input('id')[$i],
'product_id'=>$parentproduct->id,
'title' =>$request->input('title')[$i],
'language' => $request->input('language')[$i],
);
DB::table('products_translations')->insert($insertprod);
}
ProductsTranslation::insert($insertprod);
DB::table('products_translations')->insert($insertprod);
// DB::table('products_translations')->update(['change' => Input::all()]);
DB::table('products_translations')->insert($insertprod);
//ProductsTranslation::create($insertprod);
dd($insertprod);
}
When i remove the comment from the line of create
ProductsTranslation::create($insertprod);
It's getting me an error that can't update or insert FK Product_id !
How can save that array to my db ?