Insert data using seeder in Laravel 8

Use Laravel seeder to insert data to database in laravel 8

Posted by Luke Beeno on May 4, 2021

Insert data using seeder in Laravel 8

Use Laravel seeder to insert data to database in laravel 8

Posted by Luke Beeno on May 4, 2021

In this tutorial you will be shown how to use seeding to insert data in database.

Step 1. Create seeder by executing command:

php artisan make:seeder UserSeeder

Go to "database/seeders" and edit "UserSeeder.php" file

namespace Database\Seeders; 

use Illuminate\Database\Seeder;

use Illuminate\Support\Facades\DB; 

use Illuminate\Support\Facades\Hash; 

use Illuminate\Support\Str;

class UserSeeder extends Seeder 

{     

  /**   

   * Run the database seeders.   

   *    

   * @return void   

   */   

 public function run()   

  {         

   DB::table('users')->insert([    

         'name' => 'username',  

         'email' => 'username@gmail.com',   

         'password' => Hash::make('password'),   

      ]);    

  }

}

Step 2. Place UserSeeder class in the DatabaseSeeder file

Go to "database/seeders" and edit "DatabaseSeeder.php" file

namespace Database\Seeders;

use Illuminate\Database\Seeder;

class DatabaseSeeder extends Seeder {

    /**

     * Seed the application's database.

     *

     * @return void

     */

    public function run()

    {

        // call seeders needed for default setup

        $this->call([

            UserSeeder::class,

        ]);

    }

}

Step 3 execute command:

php artisan db:seed

Now check database to see user inserted.

If you create other seeders and you want to execute them all together just place it in the DatabaseSeeder file and run the execution in step 3. If you wish to run seed on one table at a time, example if you want to run only UserSeeder.

Just execute php artisan db:seed --class=UserSeeder.

If you want to clear the data you just seeded, execute command php artisan migrate:rollback

If you want to drop the table or tables and completely re-run the process in order to re-seed data, execute command 

php artisan migrate:fresh --seed

Step 3 execute command:

php artisan db:seed

Now check database to see user inserted.

If you create other seeders and you want to execute them all together just place it in the DatabaseSeeder file and run the execution in step 3. If you wish to run seed on one table at a time, example if you want to run only UserSeeder.

Just execute php artisan db:seed --class=UserSeeder.

If you want to clear the data you just seeded, execute command php artisan migrate:rollback

If you want to drop the table or tables and completely re-run the process in order to re-seed data, execute command: 

php artisan migrate:fresh --seed