Home > Net >  How to use createMany
How to use createMany

Time:01-26

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:

Print Data

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(),
];

CodePudding user response:

If you using Laravel 8 try to use upsert

Order::upsert($values,'order_number');
  • Related