In this tutorial you will be shown how to use seeding to insert data in database.
Step 1. Create seeder by executing command:
php artisan make:seeder UserSeeder
Go to "database/seeders" and edit "UserSeeder.php" file
You can use one of the example below to create one user or multiple users. The model factory will be used in a couple of the examples. Laravel 9 comes default with the UserFactory class, however if you are planning to use factory on another model you will have to create the factory for it.
Use factory to seed one user:
User::factory()->create([
'name' => 'Test User',
'email' => 'test@example.com',
]);
Use factory to seed multiple users:
User::factory(10)->create();
Use the DB:
DB::table('users')->insert([
'name' => 'username',
'email' => 'username@gmail.com',
'password' => Hash::make('password'),
]);
Here is the last example in the UserSeeder:
namespace Database\Seeders;
use Illuminate\Database\Seeder;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Hash;
use Illuminate\Support\Str;
class UserSeeder extends Seeder
{
/**
* Run the database seeders.
*
* @return void
*/
public function run()
{
DB::table('users')->insert([
'name' => 'username',
'email' => 'username@gmail.com',
'password' => Hash::make('password'),
]);
}
}
Step 2. Place UserSeeder class in the DatabaseSeeder file
Go to "database/seeders" and edit "DatabaseSeeder.php" file
namespace Database\Seeders;
use Illuminate\Database\Seeder;
class DatabaseSeeder extends Seeder {
/**
* Seed the application's database.
*
* @return void
*/
public function run()
{
// call seeders needed for default setup
$this->call([
UserSeeder::class,
]);
}
}
Step 3 execute command:
php artisan db:seed
Now check database to see user inserted.
If you create other seeders and you want to execute them all together just place it in the DatabaseSeeder file and run the execution in step 3. If you wish to run seed on one table at a time, example if you want to run only UserSeeder.
Just execute:
php artisan db:seed --class=UserSeeder
If you want to clear the data you just seeded, execute command php artisan migrate:rollback
If you want to drop the table or tables and completely re-run the process in order to re-seed data, execute command
php artisan migrate:fresh --seed
Step 3 execute command:
php artisan db:seed
Now check database to see user inserted.
If you create other seeders and you want to execute them all together just place it in the DatabaseSeeder file and run the execution in step 3. If you wish to run seed on one table at a time, example if you want to run only UserSeeder.
Just execute:
php artisan db:seed --class=UserSeeder
If you want to clear the data you just seeded, execute command:
php artisan migrate:rollback
If you want to drop the table or tables and completely re-run the process in order to re-seed data, execute command:
php artisan migrate:fresh --seed