How to Bulk insert Multiple Records in Laravel

Sovary November 5, 2022 864
1 minute read

In this tutorial we will show you how to implement insert multiple rows in Larval project. We write this article to show examples in different way of add multiple records. If we are working on import module to insert multiple records at a time, we should know how to insert bulk records in database. This method will help reduce connectivity and resources processing. The solution below will help you to create multiple records in Laravel project with single query builder or eloquent.

We will use multidimensional array to store associative array and insert multiple records by using DB:insert(). Let's check below example.

You can use this example with the versions of laravel 6, laravel 7, laravel 8, and laravel 9.

Example #1 - Query Builder

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use DB;

class TestController extends Controller
{

    public function index()
    {
        $data= [
            ['title'=>'Insert Multiple Record','description'=>'Description anything'],
            ['title'=>'Insert Multiple Record 1','description'=>'Description anything'],
            ['title'=>'Insert Multiple Record 2','description'=>'Description anything']
        ];

        DB::table("articles")->insert($data);
    }
}

Example #2 - Eloquent

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\Http\Model\Article;

class TestController extends Controller
{

    public function index()
    {
        $data= [
            ['title'=>'Insert Multiple Record','description'=>'Description anything'],
            ['title'=>'Insert Multiple Record 1','description'=>'Description anything'],
            ['title'=>'Insert Multiple Record 2','description'=>'Description anything']
        ];

        Article::insert($data);
    }
}

NOTE: above examples will not insert timestamp, so you have to add 'created_at'=>date('Y-m-d H:i:s'), 'modified_at'=> date('Y-m-d H:i:s')

You might also like...

 

Laravel  PHP  Laravel 9  Query Builder 
Author

As the founder and passionate educator behind this platform, I’m dedicated to sharing practical knowledge in programming to help you grow. Whether you’re a beginner exploring Machine Learning, PHP, Laravel, Python, Java, or Android Development, you’ll find tutorials here that are simple, accessible, and easy to understand. My mission is to make learning enjoyable and effective for everyone. Dive in, start learning, and don’t forget to follow along for more tips and insights!. Follow him