Laravel insertGetId multiple Rows Example

10-Apr-2023

.

Admin

Laravel insertGetId multiple Rows Example

Hi Dev,

In this blog, I will show you how to insert multiple record using insertGetId in laravel application. We will learn laravel multiple insert and get all insert record id.

The use of insertGetId query in laravel used to insert record and get insert record id. If the table has an auto-incrementing id, use the insertGetId method to insert a record and then retrieve the ID:

When using PostgreSQL the insertGetId method expects the auto-incrementing column to be named id. If you would like to retrieve the ID from a different "sequence", you may pass the column name as the second parameter to the insertGetId method.

Query 1


/**

* The attributes that are mass assignable.

*

* @var array

*/

public function index()

{

$myarray = [

['name'=> 'one', 'email' => 'one@gmail.com'],

['name'=> 'two', 'email' => 'two@gmail.com'],

['name'=> 'three', 'email' => 'three@gmail.com'],

];

foreach ($myarray as $key => $value) {

$id[] = User::insertGetId(

['email' => $value['email'],'name' => $value['name']]

);

}

}

Query 2

/**

* The attributes that are mass assignable.

*

* @var array

*/

public function index()

{

$myarray = [

['name'=> 'one', 'email' => 'one@gmail.com'],

['name'=> 'two', 'email' => 'two@gmail.com'],

['name'=> 'three', 'email' => 'three@gmail.com'],

];

foreach ($myarray as $key => $value) {

$id[] = DB::table('users')->insertGetId(

['email' => $value['email'],'name' => $value['name']]

);

}

}

It will help you...

#Laravel 7

#Laravel

#Laravel 6