32

I'm trying to save multiple records via

AppSettings::create(
    [
        'name' => 'mail_host',
        'type' => $emailsettingstype->id,
        'value' => '',

    ],
    [
        'name' => 'mail_port',
        'type' => $emailsettingstype->id,
        'value' => '',    
    ],
    [
        'name' => 'mail_username',
        'type' => $emailsettingstype->id,
        'value' => '',
    ],
);

But from the above, only the first array is getting created. Where am i going wrong? Any help is appreciated.

Maik Lowrey
  • 15,957
  • 6
  • 40
  • 79
Geoff
  • 6,277
  • 23
  • 87
  • 197

6 Answers6

29

I think this should do

AppSettings::createMany([
    [
        'name'=>'mail_host',
        'type'=>$emailsettingstype->id,
        'value'=>'',

    ],
    [
        'name'=>'mail_port',
        'type'=>$emailsettingstype->id,
        'value'=>'',

    ],
    [
        'name'=>'mail_username',
        'type'=>$emailsettingstype->id,
        'value'=>'',
    ],
]);

Make sure you're passing an array of arrays, not a params of array.

UPDATE, you can use Model::insert() although according to what I've read, that method doesn't create/update the timestamps.

Wreigh
  • 3,215
  • 16
  • 37
  • 4
    This answer was for an earlier version of Laravel, unfortunately, I'm no longer up to date and not sure how this should be done in the latest major version. Id appreciate if someone would actually update this, if that adds any value though. – Wreigh Nov 03 '20 at 01:10
  • 9
    Call to undefined method App\Models\Post::createMany() , Version 8 of laravel – Waleed Khaled Sep 19 '21 at 18:40
  • Model::insert() works on Laravel 7 – user3613026 Oct 06 '21 at 13:57
  • 3
    https://laravel.com/docs/9.x/eloquent-relationships#the-create-method This advice does not work for version 9 or any previous Laravel version. According to the official Laravel documentation, the method createMany() does "create multiple related models", meaning it works only on related models, not on the model directly, as written above. – azurecorn Dec 09 '22 at 01:07
24

You can just use Eloquent::insert() link as below:

AppSettings::insert([
    [
        'name'=>'mail_host',
        'type'=>$emailsettingstype->id,
        'value'=>'',

    ],
    [
        'name'=>'mail_port',
        'type'=>$emailsettingstype->id,
        'value'=>'',

    ],
    [
        'name'=>'mail_username',
        'type'=>$emailsettingstype->id,
        'value'=>'',
    ],
]);

The problem with above is that it won't update timestamps, find examples here

Ganesh Ghalame
  • 6,367
  • 3
  • 24
  • 29
5

The Create many Method createMany is available on relationship check reference to this link and this documentation from laravel

so far my example look like this.

I have two models Pricing and AvailableService Model

Pricing Model

namespace App;
use Illuminate\Database\Eloquent\Model;
class Pricing extends Model
{
    protected $fillable = ["name", "price"];
    public function available(){
        return $this->hasMany(AvailableService::class, "pricing_id", "id");
    }
}

And the AvailableServiceMode look like this

namespace App;
use Illuminate\Database\Eloquent\Model;
class AvailableService extends Model
{
    protected $fillable = ["pricing_id", "service_id"];
    public function service(){
        return $this->belongsTo(Service::class, "service_id", "id");
    }
}

So createMany operation look like this

$insertMany = Pricing::create(['name'=>request('name')]);
$insertMany->available()->createMany([
      ['service_id'=>1],
      ['service_id'=>2],
      ['service_id'=>3],
      ['service_id'=>4],
      ['service_id'=>5],
]);

And it works for, you can give it a try too. THANKS

Karim Pazoki
  • 951
  • 1
  • 13
  • 34
Ruberandinda Patience
  • 3,435
  • 3
  • 20
  • 18
4

If you want to store multiple record in seeder use this method instead of insert because in my case I want to slug automatically created using spatie/laravel-sluggable pkg. If you used the insert or DB technique then you have to give the value for slug field also.

CategorySeeder

<?php

namespace Database\Seeders;

use App\Servcategory;
use Illuminate\Database\Seeder;

class CategorySeeder extends Seeder
{
    /**
     * Run the database seeds.
     *
     * @return void
     */
    public function run()
    {
        $categories = [
            [
                'name' => 'Automotive',
                // 'slug' => 'automotive',
            ],
            [
                'name' => 'Business Services',
                // 'slug' => 'business-services',
            ],
            [
                'name' => 'Computer, Telecom & IT Services',
                // 'slug' => 'computer-telecom-&-it-services',
            ],
            [
                'name' => 'Education & Training',
                // 'slug' => 'education-&-training',
            ],
            [
                'name' => 'Finance',
                // 'slug' => 'finance',
            ],
            [
                'name' => 'Hospitals, Clinic, Medical',
                // 'slug' => 'hospitals-clinic-medical',
            ],
            [
                'name' => 'Real Estate, Construction, Property',
                // 'slug' => 'real-estate-construction-property',
            ],
            [
                'name' => 'Travel,Toursim & Hotels',
                // 'slug' => 'travel-toursim-&-hotels',
            ],
        ];

        // Servcategory::insert($categories);
        collect($categories)->each(function ($category) { Servcategory::create($category); });
    }
}

Neeraj Tangariya
  • 1,159
  • 1
  • 17
  • 29
0

In case some one searching for eloquent model, I used the following method:

foreach($arCategories as $v)
{                
    if($v>0){
        $obj = new Self(); // this is to have new instance of own
        $obj->page_id = $page_id;
        $obj->category_id = $v;
        $obj->save();
    }
}

$obj = new Self(); is a must otherwise it only saves single record when $this is used.

dazed-and-confused
  • 1,293
  • 2
  • 11
  • 19
justnajm
  • 4,422
  • 6
  • 36
  • 56
-2

in seeder create an array and do foreach with Model::create(). All your records will be with timestamps


protected $array = [
    [...],
    [...],
    [...]
];

public function run()
{
    foreach ($this->array as $value) {
        Model::create($value);
    }
}

nurzzzone
  • 35
  • 3
  • Hey Dude it's incorrect, because for example if had 100000 records, it has to run 100000 queries and it's so harmful and terrible for your project – Azade Jul 17 '23 at 06:54