Hey there! If you're working on a Laravel 12 project and need sample data for testing, database seeders can save you a lot of time. Instead of manually inserting data, Laravel's seeder lets you generate test data quickly and efficiently.
In this guide, I'll show you how to create and use a database seeder step by step.
Steps to Create a Database Seeder in Laravel 12
Run the following Artisan command to generate a new seeder file:
php artisan make:seeder UserSeeder
This will create a UserSeeder.php file in the database/seeders directory.
Open database/seeders/UserSeeder.php and modify the run method to insert test data.
<?php
namespace Database\Seeders;
use Illuminate\Database\Seeder;
use App\Models\User;
use Illuminate\Support\Facades\Hash;
class UserSeeder extends Seeder
{
public function run()
{
User::create([
'name' => 'John Doe',
'email' => '[email protected]',
'password' => Hash::make('password'),
]);
}
}
Now, you need to execute the seeder using this command:
php artisan db:seed --class=UserSeeder
This will insert the sample user data into your database.
If you need multiple users, use a factory instead. Update the UserSeeder.php file.
public function run()
{
\App\Models\User::factory(10)->create();
}
Then, run the seeder again.
php artisan db:seed --class=UserSeeder
To run all seeders in the DatabaseSeeder.php file, first add your seeder inside the run method:
public function run()
{
$this->call([
UserSeeder::class,
]);
}
Then, run this command to execute all seeders:
php artisan db:seed
You might also like: