Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Saving multiple records in a laravel eloquent create

Tags:

php

laravel

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.

like image 878
Geoff Avatar asked Jan 27 '18 02:01

Geoff


People also ask

What is difference between create and save in Laravel?

What is difference between create and save in Laravel? Save can be used to both create a new Record and update a existing record . Whereas create is used to create a new record by providing all required field at one time .

What is Save () in Laravel?

save() save() method is used both for saving new model, and updating existing one. here you are creating new model or find existing one, setting its properties one by one and finally saves in database.

How do I combine two tables in eloquent Laravel?

If you want to join two or multiple tables in laravel then you can use laravel eloquent join(), left join(), right join(), cross join(). And another option to join two or multiple table, you can use laravel eloquent relationships instead of laravel join.


4 Answers

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.

like image 129
Wreigh Avatar answered Oct 07 '22 18:10

Wreigh


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

like image 43
Ganesh Ghalame Avatar answered Oct 07 '22 18:10

Ganesh Ghalame


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

like image 34
Ruberandinda Patience Avatar answered Oct 07 '22 19:10

Ruberandinda Patience


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); });
    }
}

like image 37
Neeraj Tangariya Avatar answered Oct 07 '22 18:10

Neeraj Tangariya