CI 4 Insert Rows in Bulk

Share this Article

In case if we want to insert rows in bulk then we have a method available in CodeIgniter 4 which we call via Model object.

# Load model

use App\Models\StudentModel;

# Creating model instance

$object = new StudentModel();

# Insert Rows
$object->insertBatch([ [], [], [], ... ]);
<?php

namespace App\Controllers;

use App\Controllers\BaseController;
use App\Models\StudentModel;

class StudentController extends BaseController
{
	public function insertData()
	{
		$object = new StudentModel();

		// Insert rows in bulk
		$object->insertBatch([
			[
				"name" => "Sanjay Kumar",
				"email" => "test@gmail.com",
				"mobile" => "9879638521"
			],
			[
				"name" => "Ashish Kumar",
				"email" => "ashish@gmail.com",
				"mobile" => "6541231333"
			]
		]);

		//...
	}
}

Above code will insert rows in bulk inside associated table for StudentModel.

Learn Web Development Courses @ $4 only.
Web Development Courses @ $4