Database seeder in Laravel is the process of populating your application's database with sample or dummy data. It's particularly useful during development and testing phases, allowing you to quickly populate your database with data that resembles what your application will encounter in production.
Laravel provides a convenient way to generate seeders using Artisan, its command-line tool. You can create a seeder using the make:seeder
command:
php artisan make:seeder UsersTableSeeder
This command will generate a new seeder class in the database/seeders
directory.
Open the generated seeder file (UsersTableSeeder.php
, in this case) and define the logic to populate your database with sample data. You can use Eloquent models to create records, or you can use the query builder directly.
For example:
use Illuminate\Database\Seeder;
use App\Models\User;
class UsersTableSeeder extends Seeder
{
public function run()
{
User::create([
'name' => 'John Doe',
'email' => 'john@example.com',
'password' => bcrypt('password'),
]);
// Add more sample data as needed
}
}
You can call your seeders using the db:seed
Artisan command. If you want to run a specific seeder, you can specify its class name using the --class
option:
php artisan db:seed --class=UsersTableSeeder
If you want to run all seeders, you can simply run:
php artisan db:seed
You can also use the --force
option to run seeders in production.
By default, Laravel includes a DatabaseSeeder
class within the database/seeders
directory. This class is intended to be a central location for all of your seeder calls. You can call additional seeders within this class if needed.
For example:
use Illuminate\Database\Seeder;
class DatabaseSeeder extends Seeder
{
public function run()
{
$this->call([
UsersTableSeeder::class,
// Add more seeders here
]);
}
}
Then, to run all seeders, you can simply execute:
php artisan db:seed
Database seeding in Laravel is a powerful feature that can significantly speed up the process of developing and testing your applications by providing a quick and easy way to populate your database with sample data.