Maulik Bhatt
Maulik Bhatt

Reputation: 33

Laravel Eloquent: Is it possible to use "create" method for inserting multiple records as array?

As Laravel document says we can insert "a" record using create eloquent method

$flight = App\Flight::create(['name' => 'Flight 10']);

Is it possible to insert multiple records using create method without loop. i.e.

$flight = App\Flight::create([['name' => 'Flight 10'], ['name' => 'Flight 11']]);

Currently I am using insert method but it does not take care of created_at and updated_at values which I have to make fillable.

$flight = App\Flight::insert([['name' => 'Flight 10'], ['name' => 'Flight 11']);

Upvotes: 3

Views: 5319

Answers (4)

TsaiKoga
TsaiKoga

Reputation: 13394

create() supports insert only one record.

insert() supports insert many records.

createMany() just support only for relationship, not Model.

So you only can choose insert() method for this eloquent builder.

However, you can use useCurrent() in your migration, so the default value will automatically set the current time.

$table->timestamp('created_at')->useCurrent();
$table->timestamp('updated_at')->useCurrent();

This will work to insert() method without manually set the timestamp:

$flight = App\Flight::insert([['name' => 'Flight 10'], ['name' => 'Flight 11']);

Upvotes: 9

Jithesh Jose
Jithesh Jose

Reputation: 1814

Manually fill timestamps.

$data_to_create = [
[
  'name' => 'Flight 10'
   'created_at' => date('Y-m-d H:i:s'),
   'updated_at' => date('Y-m-d H:i:s')
],
[
  'name' => 'Flight 11'
   'created_at' => date('Y-m-d H:i:s'),
   'updated_at' => date('Y-m-d H:i:s')
]
];

App\Flight::insert($data_to_create);

Upvotes: 0

pankaj sondagar
pankaj sondagar

Reputation: 56

$data = [
[
  'name' => 'Flight 10'
   'created_at' => date('Y-m-d H:i:s'),
   'updated_at' => date('Y-m-d H:i:s')
],
[
  'name' => 'Flight 11'
   'created_at' => date('Y-m-d H:i:s'),
   'updated_at' => date('Y-m-d H`enter code here`:i:s')
]

];

App\Flight::createMany($data);

Upvotes: -2

Hamelraj
Hamelraj

Reputation: 4826

insert does not add the timestamp values so you have to put manually

 $data = [
    [
      'name' => 'Flight 10'
       'created_at' => date('Y-m-d H:i:s'),
       'updated_at' => date('Y-m-d H:i:s')
    ],
    [
      'name' => 'Flight 11'
       'created_at' => date('Y-m-d H:i:s'),
       'updated_at' => date('Y-m-d H:i:s')
    ]
 ];

App\Flight::insert($data);

Upvotes: 1

Related Questions