A Laravel Seeder is a feature of the Laravel PHP framework that allows you to populate your database with test or dummy data. This is particularly beneficial during the development, testing, and demo stages of your application.
All seed classes are stored in the `database/seeders` directory. By default, a `DatabaseSeeder` class is defined for you. From this class, you may use the `call` method to run other seed classes, allowing you to control the seeding order.
To generate a seeder, you can execute the `make:seeder` Artisan command. A seeder class only contains one method by default: `run`. This method is called when the `db:seed` Artisan command is executed. Within the `run` method, you may insert data into your database however you wish. You may use the query builder to manually insert data or you may use Eloquent model factories.
Step 1 : Create a Seeder with Command
php artisan make:seeder UserSeeder
After running the command, A seeder file named `UserSeeder.php` will be created in `database/seeders` directory.
<?php
namespace Database\Seeders;
use App\Models\User;
use Illuminate\Database\Seeder;
use Illuminate\Support\Facades\Hash;
use Illuminate\Support\Str;
class UserSeeder extends Seeder
{
/**
* Run the database seeds.
*
* @return void
*/
public function run()
{
User::create([
'username' => Str::random(10),
'name' => Str::random(10),
'email' => Str::random(10).'@example.com',
'mobile' => '911234567891',
'password' => Hash::make('password'),
'status' => 1
]);
}
}
Step 2 : Using call method in DatabaseSeeder.php
The call method is used to execute additional seed classes within the DatabaseSeeder class. It allows you to break up your database seeding into multiple files so that no single seeder class becomes too large. The call method accepts an array of seeder classes that should be executed.
<?php
use Illuminate\Database\Seeder;
class DatabaseSeeder extends Seeder
{
public function run()
{
$this->call([
UserSeeder::class
]);
}
}
Step 3 : Run Seeder
php artisan db:seed
To run specific seeder use this command
php artisan db:seed –class=UserSeeder
You can also seed your database using the migrate:fresh command in combination with the -seed option. This command drops all tables, re-runs all of your migrations, and re-building your database.
php artisan migrate:fresh --seed