How to seed a database table with sample data in Laravel?

To seed a database table with sample data in Laravel, follow these steps:

  1. Create a new seeder class by executing the following command in your terminal:
php artisan make:seeder SampleDataTableSeeder

This will create a new seeder class named SampleDataTableSeeder inside the database/seeders directory.

  1. Open the SampleDataTableSeeder class and define the run() method. This method will contain the code to insert sample data into the table. For example:
use Illuminate\Database\Seeder; use App\Models\SampleData; class SampleDataTableSeeder extends Seeder { public function run() { SampleData::create([ 'column1' => 'value1', 'column2' => 'value2', ]); SampleData::create([ 'column1' => 'value3', 'column2' => 'value4', ]); // Add more sample data as needed } }
  1. Specify the seeder class in the DatabaseSeeder class located in the database/seeders directory. This class is responsible for calling all the individual seeder classes. Open the DatabaseSeeder class and call the SampleDataTableSeeder class as shown below:
use Illuminate\Database\Seeder; class DatabaseSeeder extends Seeder { public function run() { $this->call(SampleDataTableSeeder::class); } }
  1. Run the seed command to populate the table with sample data. Open your terminal and execute the following command:
php artisan db:seed

This will execute the DatabaseSeeder class and populate the specified table with sample data defined in the SampleDataTableSeeder class.

Note: Make sure you have already created the table in your database before running the seed command.