To seed a database table with sample data in Laravel, follow these steps:
php artisan make:seeder SampleDataTableSeeder
This will create a new seeder class named SampleDataTableSeeder
inside the database/seeders
directory.
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
}
}
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);
}
}
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.