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:
createMany on createMany in Laravel?
But I don’t understand how it works.
This is how the values show up:
2
Answers
createMany()
only works on relationships, what you should be using isinsert()
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:
Since you are modifying the array before creating, you can always just add the
updated_at
andcreated_at
If you using Laravel 8+ try to use upsert