16

I am inserting the data to the rows one by one, but I have heard somewhere that it requires much time if there are many data to insert. So what are the ways of inserting them all at once?

public function add(Request $request)
{
    if ($request->ajax()) {
        $books = $request->books;
        foreach ($books as $book) {
            if (!empty($book)) {
                $add = new Book;
                $add->name = $book;
                $add->user_id = Auth::user()->id;
                $add->save();
            }
        }
    }
}
Luke Berry
  • 1,927
  • 4
  • 19
  • 32
Steve
  • 1,622
  • 5
  • 21
  • 39
  • [This older question may help](http://stackoverflow.com/questions/29723865/how-to-insert-multiple-rows-from-a-single-query-using-eloquent-fluent) the latest comment on the answer links to [something helpful](https://laravel.com/docs/5.1/eloquent-relationships#inserting-related-models) –  Aug 24 '16 at 03:04
  • 3
    Possible duplicate of [Bulk Insertion in Laravel using eloquent ORM](http://stackoverflow.com/questions/12702812/bulk-insertion-in-laravel-using-eloquent-orm) – maiorano84 Aug 24 '16 at 03:04
  • (I'm not a laravel developer) It seems like any answer coming from more than a year ago wouldn't still be relevant? I guess it depends on the veraion... –  Aug 24 '16 at 03:06

5 Answers5

30
public function add(Request $request)
  {
    if($request->ajax())
    {
       $books=$request->books;
       $data = array();
       foreach($books as $book)
       {
        if(!empty($book))
        {
          $data[] =[
                    'name' => $book,
                    'user_id' => Auth::id(),
                   ];                 

       }}
      Book::insert($data);
       <!--DB::table('books')->insert($data);-->
     }}

make sure imported use Illuminate\Support\Facades\Auth;

Hamelraj
  • 4,676
  • 4
  • 19
  • 42
12

Insert multiple records using the Model

As others have pointed out, using the Query Builder is the only way to insert multiple records at a time. Fortunately Laravel and the Eloquent ORM are coupled in many useful ways. This coupling allows you to use a Model to get a Query Builder instance that is set for that Model.

// use Auth;
// use Carbon;
// use App\Book;

public function add(Request $request)
{
    if($request->ajax())
    {
        // Submitted books
        $books = $request->books;

        // Book records to be saved
        $book_records = [];

        // Add needed information to book records
        foreach($books as $book)
        {
            if(! empty($book))
            {
                // Get the current time
                $now = Carbon::now();

                // Formulate record that will be saved
                $book_records[] = [
                    'name' => $book,
                    'user_id' => Auth::user()->id,
                    'updated_at' => $now,  // remove if not using timestamps
                    'created_at' => $now   // remove if not using timestamps
                ];
            }
        }

        // Insert book records
        Book::insert($book_records);
    }
}
Qevo
  • 2,343
  • 1
  • 11
  • 17
9

You should be able to do something like below:

DB::table('users')->insert([
    ['email' => 'taylor@example.com', 'votes' => 0],
    ['email' => 'dayle@example.com', 'votes' => 0]
]);

Put all the values you want to insert in to an array and then pass it to the insert function.

Source: https://laravel.com/docs/5.1/queries#inserts

Shamintha
  • 89
  • 5
-1
foreach($request->refereename as $i =>$value)
  {
    $referees[]=[
        'refereename'=>$request->refereename[$i],
        'refereecompany'=>$request->refereecompany[$i],
        'refereephone'=>$request->refereephone[$i],
        'refereeemail'=>$request->refereeemail[$i],
        'relationship'=>$request->relationship[$i],
        'refereelocation'=>$request->refereelocation[$i],
        'created_at'=>$date,
        'updated_at'=>$date,
        ];
  }

  DB::table('db_referees')->insert($referees); // Query Builder approach 
  • 1
    Your answer could be improved with additional supporting information. Please [edit] to add further details, such as citations or documentation, so that others can confirm that your answer is correct. You can find more information on how to write good answers [in the help center](/help/how-to-answer). – Community Aug 05 '23 at 10:01
-3

If you need Eloquent model events - there is no other way to insert multiple models. In other way - check Anushan W answer

Community
  • 1
  • 1
Bogdan Koliesnik
  • 780
  • 6
  • 14