Hello i am new to laravel and i have many arrays that i want to insert in database with createMany()
this is my code what i have done so far:
public function store(Request $request)
{
$request->validate([
'order_number' => 'required',
'client' => 'required',
'products' => 'required',
'amount' => 'required',
'description' => 'required',
]);
for($i = 0; $i < count($request->products); $i )
{
$values[] = [
'order_number' => $request->order_number,
'client' => $request->client,
'products' => $request->products[$i],
'amount' => $request->amount[$i],
'description' => $request->description,
];
}
dd($values);
Order::createMany($values);
return redirect('/')->with('msg', 'Order Saved successfully!');
}
I saw on internet and documentation examples like this:
CodePudding user response:
If you using Laravel 8 try to use upsert
Order::upsert($values,'order_number');
CodePudding user response:
createMany()
only works on relationships, what you should be using is insert()
So Order::insert($values);
You can read more on insert here: https://laravel.com/docs/9.x/queries#insert-statements
Because you want the timestamps to be updated then what you can do is this:
foreach($values as $value){
Order::create($value);
}
Since you are modifying the array before creating, you can always just add the updated_at
and created_at
$values[] = [
'order_number' => $request->order_number,
'client' => $request->client,
'products' => $request->products[$i],
'amount' => $request->amount[$i],
'description' => $request->description,
'updated_at' => now(),
'created_at' => now(),
];