How to create a seeder in Laravel?

Seeders are used to populate your application’s database with dummy or test data. They are especially useful during the development and testing phases. Laravel provides a convenient way to generate and run seeders using its built-in Artisan command-line interface.

To create a seeder in Laravel, follow these steps:

1 . Generate a new seeder file:

Open your command-line interface (CLI) and navigate to your Laravel project’s root directory. Then, run the following command to generate a new seeder file:

php artisan make:seeder SeederName

Replace SeederName with the desired name for your seeder. This command will create a new seeder file in the database/seeders directory.

2 . Open the generated seeder file:

After running the command above, Laravel will create the seeder file for you. You can open it by going to the database/seeders directory and locating the file with the name you specified. The file will contain a run() method.

3 . Define the data to be seeded:

Inside the run() method, you can write code to generate and insert dummy data into your database. You can use Laravel’s Eloquent models or the query builder to interact with the database. Here’s an example of seeding a users table with two dummy users using the User model:

use Illuminate\Database\Seeder;
use App\Models\User;

class SeederName extends Seeder
{
    public function run()
    {
        User::create([
            'name' => 'John Doe',
            'email' => 'john@example.com',
            'password' => bcrypt('secret'),
        ]);

        User::create([
            'name' => 'Jane Smith',
            'email' => 'jane@example.com',
            'password' => bcrypt('password'),
        ]);
    }
}

4 . Run the seeder:

To execute the seeder and populate the database, you need to run the following command in your CLI:

php artisan db:seed --class=SeederName

Replace SeederName with the actual name of your seeder class. This command will run the run() method defined in your seeder file and insert the dummy data into the database.

Alternatively, you can run all the seeders at once by using the db:seed command without specifying a class:

php artisan db:seed

That’s it! You have successfully created a seeder in Laravel and populated your database with dummy data. Remember to adjust the data and logic in the seeder file based on your specific needs.

Run Specific Seeder file.

php artisan db:seed --class=UserSeeder

You may also use.

php artisan migrate:fresh --seed --seeder=UserSeeder