How To Bulk Insert Using Laravel Eloquent (With Timestamps)

When working with large datasets it is useful to have a way to insert multiple records into a database at once. Laravel Eloquent allows a simple way to bulk insert by using the insert method.

To bulk insert records using Laravel Eloquent, use Model::insert($data). The $data parameter should be an array of arrays containing the record data. This method allows efficient insertion of multiple records in a single operation.

Note that when performing a bulk insert, timestamps are not automatically generated for each record. In this tutorial, I will guide you through the process of performing a bulk insert while ensuring that the created_at and updated_at timestamps are correctly filled.

Step 1: Create Model and Migration

Open your terminal and navigate to your Laravel project directory. Run the following command to generate the model and migration files:

php artisan make:model Movie -m

The above command will create a “Movie” model file in the “app/Models” directory and a migration file in the “database/migrations” directory.

Step 2: Define the Migration Schema

Open the generated migration file (it should be named something like “create_movies_table”) in the “database/migrations” directory. Within the up method, you can define the schema for the “movies” table using Laravel’s Schema Builder. Modify the up method as follows:

database/migrations/2023_06_12_214046_create_movies_table.php
<?php

use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;

return new class extends Migration
{
    /**
     * Run the migrations.
     */
    public function up(): void
    {
        Schema::create('movies', function (Blueprint $table) {
            $table->id();
            $table->string('title');
            $table->string('director');
            $table->timestamps();
        });
    }

    /**
     * Reverse the migrations.
     */
    public function down(): void
    {
        Schema::dropIfExists('movies');
    }
};

In the above code, we use the id() method to create the default “id” column as the primary key. Then, we add the “title” and “director” columns as strings. Finally, we call the timestamps() method to automatically add the “created_at” and “updated_at” columns for the default Laravel timestamps.

Note that Laravel will autofill a Model’s created_at and updated_at timestamps automatically when using the Eloquent create, update and save methods but not on mass insert using the insert method.

Step 3: Run the Migration

Save the migration file and open your terminal and run the migration to create the “movies” table using this command:

php artisan migrate

This command will execute the migration and create the “movies” table in your database with the specified columns.

Step 4: Prepare the Data for Bulk Insert

In this example, let’s define an array of data that we want to bulk insert into our table movies later on. Each array in the array $data represents a record and should contain keys corresponding to the table columns and values we wish them to have. Finally, in order to add the created_at and updated_at timestamps, we iterate over the array and append the timestamp values to our array using Carbon, which is included in Laravel by default. Here’s an example code snippet:

use Carbon\Carbon;
use App\Models\Movie;

$data = [
    [
        'title' => 'Iron Man 3',
        'director' => 'Shane Black',
    ],
    [
        'title' => 'Black Widow',
        'director' => 'Cate Shortland',
    ],
    [
        'title' => 'Guardians of the Galaxy',
        'director' => 'James Gunn',
    ],
    // Add more records here
];

$timestamp = Carbon::now();

foreach ($data as &$record) {
    $record['created_at'] = $timestamp;
    $record['updated_at'] = $timestamp;
}

Step 5: Perform Bulk Insertion

Now that we have prepared the data with the timestamps, we can use the insert method provided by Eloquent to perform the bulk insertion. Here’s an example code snippet:

Movie::insert($data);

By using the insert method on the Movie model, Laravel will efficiently insert all the records in a single database query, reducing the overhead of multiple insert statements.

Conclusion

Laravel Eloquent provides a convenient method for bulk inserting records into a database using the insert method. This allows for efficient bulk insertion of multiple records in a single operation. While the insert method does not automatically generate timestamps for each insert, we learned how to append them to our array using Carbon.

By following the steps outlined in this tutorial, you can create a model and migration, define the schema, run the migration, prepare the data for bulk insert, and perform the bulk insertion using Eloquent. This approach helps streamline the insertion process, especially when dealing with large datasets. Happy coding!

Johan van den Broek

Johan is the creator of laracoding.com. As a child, he began tinkering with various programming languages, many of which have been long forgotten today. Currently, he works exclusively with PHP and Laravel, and his passion for programming remains to this day.

Leave a Reply

Your email address will not be published. Required fields are marked *

Recent Posts