How to Bulk insert Multiple Records in Laravel

Sovary November 5, 2022 628
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

Founder of CamboTutorial.com, I am happy to share my knowledge related to programming that can help other people. I love write tutorial related to PHP, Laravel, Python, Java, Android Developement, all published post are make simple and easy to understand for beginner. Follow him