Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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
like image 504
lewis4u Avatar asked Sep 03 '25 04:09

lewis4u


1 Answers

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.

like image 70
Rumel Avatar answered Sep 05 '25 01:09

Rumel