skip to Main Content

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?

Documentation

But I don’t understand how it works.

This is how the values show up:

Print Data

2

Answers


  1. 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(),
    ];
    
    Login or Signup to reply.
  2. If you using Laravel 8+ try to use upsert

    Order::upsert($values,'order_number');
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search