Here's a concise answer on how to use Laravel's database seeding feature in conjunction with migrations:
Creating a Seeder
You can generate a new seeder using the `make:seeder` Artisan command:
php artisan make:seeder UsersTableSeeder
This will create a new seeder class in the `database/seeders` directory.
Defining Seeding Logic
In the generated seeder class, you can define the data to be inserted into the database. For example:
php
public function run()
{
DB::table('users')->insert([
'name' => 'John Doe',
'email' => '[email protected]',
'password' => bcrypt('secret'),
]);
}
Running Seeders
To seed your database, use the `db:seed` command:
php artisan db:seed
This will execute the `run()` method of all seeder classes.
Combining Migrations and Seeders
You can combine migrations and seeders by calling a seeder from within a migration's `up()` method:
php
public function up()
{
Schema::create('users', function (Blueprint $table) {
$table->id();
$table->string('name');
$table->string('email')->unique();
$table->timestamp('email_verified_at')->nullable();
$table->string('password');
$table->rememberToken();
$table->timestamps();
});
$this->call([
UsersTableSeeder::class,
]);
}
This will create the `users` table and immediately seed it with data from the `UsersTableSeeder` class.
To rollback the migration and remove the seeded data, use the `migrate:rollback` command.
By combining migrations and seeders, you can easily manage your database schema and populate it with initial data in a version-controlled manner.
Citations:[1] https://www.javatpoint.com/laravel-migration
[2] https://laravel.com/docs/5.0/migrations
[3] https://dev.to/techtoolindia/how-to-create-migration-in-laravel--2532
[4] https://laravel.com/docs/5.2/migrations
[5] https://laravel.io/forum/strategy-for-multi-change-migrations