Running seeders in Laravel is an essential task when you need to populate your database with test or default data. Seeders are PHP classes that allow you to define a set of records to be inserted into your database. Whether you're setting up initial data or testing, understanding how to run seeders is crucial.
To run seeders in Laravel, follow these steps:
1. Create a Seeder Class: Use the Artisan command to generate a seeder class:
php artisan make:seeder SeederName
This command will create a new seeder file in the database/seeders
directory.
2. Define Data in the Seeder: Open the generated seeder file and define the data to be inserted in the run
method:
public function run()
{
// Example: Inserting data into the 'users' table
DB::table('users')->insert([
'name' => 'John Doe',
'email' => 'johndoe@example.com',
'password' => bcrypt('password'),
]);
}
3. Run the Seeder: Execute the seeder using the Artisan command:
php artisan db:seed --class=SeederName
Replace SeederName
with the name of your seeder class.
4. Run All Seeders: To run all seeders at once, you can use the following command:
php artisan db:seed
php artisan make:seeder UserSeeder
In the UserSeeder
class, you can define multiple user records to be inserted into the database.
php artisan db:seed --class=UserSeeder
This command runs only the UserSeeder
class, allowing you to seed specific tables as needed.
If you've created multiple seeders, you can run them all with:
php artisan db:seed
Jorge García
Fullstack developer