Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Insert Multiple Records At Once With Laravel

Tags:

php

laravel

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();
            }
        }
    }
}
like image 852
Steve Avatar asked Aug 24 '16 02:08

Steve


People also ask

How can I insert multiple rows in a single query in database?

INSERT-SELECT-UNION query to insert multiple records Thus, we can use INSERT-SELECT-UNION query to insert data into multiple rows of the table. The SQL UNION query helps to select all the data that has been enclosed by the SELECT query through the INSERT statement.

What is difference between insert and create in laravel?

create() is a function from Eloquent, insert() - Query Builder. In other words, create is just an Eloquent model function that handles the creation of the object to the DB (in a more abstract way). Insert however tries to create the actual query string.

What is Upsert in laravel?

Laravel 8. x's query builder comes packed with a method called upsert that will let you insert (multiple) rows that do not exist and update the rows that already exist with the new values. So, for instance, let's say, you have a table called books and it contains the following records right now.

What is DB row in laravel?

DB::raw() is used to make arbitrary SQL commands which aren't parsed any further by the query builder. They therefore can create a vector for attack via SQL injection. So in my example I guess that the query with DB::raw is faster since laravel doesn't check or validate anything.


3 Answers

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;

like image 87
Hamelraj Avatar answered Oct 15 '22 18:10

Hamelraj


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);
    }
}
like image 23
Qevo Avatar answered Oct 15 '22 17:10

Qevo


You should be able to do something like below:

DB::table('users')->insert([
    ['email' => '[email protected]', 'votes' => 0],
    ['email' => '[email protected]', '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

like image 22
Shamintha Avatar answered Oct 15 '22 17:10

Shamintha