lewis4u
lewis4u

Reputation: 15047

Laravel 5 - How to seed table automatically after deploying an app?

I have a certain data that must be in table in order for my app to work, otherwise i get an error message.

For example if YOU or anyone else pulled my app from github and if you run php artisan migrate and then try to test the app you would get an error: data doesn't exist or something like that. and it's because there is no data in table.

So ideal solution would be after running:

 php artisan migrate

that you also get this needed data in that table.

This should be done somehow with the seeder but i don't know how. Can anyone help and give me an example?

How to make a seed for this data that should go into car_company table:

id car_company

1 Volkswagen

2 Mercedes

3 Audi

4 Porsche

there are 4 rows and i want to insert them after running

 php artisan db:seed

Upvotes: 4

Views: 3638

Answers (3)

Rumel
Rumel

Reputation: 319

At first run the following command :

php artisan make:seeder CarCompanyTableSeeder. This will create class CarCompanyTableSeeder in database\seeds.

enter image description here

Inside the function public function run() please add the following codes :

public function run()
    {
        $data = array(
            array(
                'id'            =>    1,
                'car_company'   =>   'Volkswagen'
            ),
            array(
                'id'            =>    2,
                'car_company'   =>   'Mercedes'
            ),
            array(
                'id'            =>    3,
                'car_company'   =>   'Audi'
            ),
            array(
                'id'            =>    4,
                'car_company'   =>   'Porsche'
            )
        );

        DB::table('car_company')->insert($data);
    }

There is another class class DatabaseSeeder extends Seeder in database\seeds. Inside the class there is a function run(). Add the following code there :

public function run()
    {
        Model::unguard();

        $this->call(CarCompanyTableSeeder::class);

        Model::reguard();
    }

Now, when you will run php artisan db:seed, then your desired values will be inserted there.

Upvotes: 7

Marcin Nabiałek
Marcin Nabiałek

Reputation: 111859

At the moment for such situations I use database migrations. You don't need to have in migrations only creating database structure, but you can also in migrations add data to database so it will be enought to run php artisan migrate to create database structure and create required data in database.

Upvotes: 0

Raymond Cheng
Raymond Cheng

Reputation: 2505

After run php artisan migrate you need run php artisan db:seed, to write seeds to database, you can follow this instructions: https://laravel.com/docs/5.2/seeding#using-model-factories

another useful package is: https://github.com/fzaninotto/Faker, help you fake datas to database.

Upvotes: 0

Related Questions