Skip to content
Advertisement

Insert an array using seeders with laravel

Hi I want to insert this array using seeders into Laravel framework:

<?php
        $countries = array("Afghanistan", "Albania", "Algeria", "American Samoa", "Andorra");
?>

I read that I can do it this way:

<?php
    DB::table('users')->insert($users);
?>

But I want to insert these countries in the column name of my table:

<?php
    public function run()
        {
            DB::table('countries')->insert([
                'name' => 'EE.UU',
            ]);
        }
?>

I don’t want to do it manually, I want to insert the array of above completely.

Thank you so much.

Advertisement

Answer

Try this solution

$countries = array("Afghanistan", "Albania", "Algeria", "American Samoa", "Andorra");
$insert = [];
foreach ($countries as $name) {
    $insert[] = [
        'name' => $name
    ];
}
DB::table('countries')->insert($insert);
User contributions licensed under: CC BY-SA
7 People found this is helpful
Advertisement