Creating Data Using Seeder in Laravel

In Laravel, seeder are used to populate the database with initial or dummy data. They provide a convenient way to create and insert data into database tables. Here's a step-by-step guide on using seeder in Laravel:

 

Create a Seeder

To create a new seeder, you can use the make:seeder Artisan command. For example, to create a seeder for the "users" table, run the following command:

php artisan make:seeder UsersTableSeeder

 

Define Data

Open the generated seeder file in the database/seeders directory. In the run method, you can define the data that you want to seed into the database. You can use Laravel's query builder or Eloquent ORM to insert the data.

public function run()
{
    DB::table('users')->insert([
        [
            'name' => 'John Doe',
            'email' => '[email protected]',
            'password' => bcrypt('password123'),
        ],
        [
            'name' => 'Jane Doe',
            'email' => '[email protected]',
            'password' => bcrypt('password456'),
        ],
        // Add more data as needed
    ]);
}

 

Run the Seeder

To execute the seeder and insert the data into the database, use the db:seed Artisan command. By default, all seeder will be run. If you want to run a specific seeder, you can use the --class option.

php artisan db:seed

 

Seeder and Rollback

Seeder can be rolled back just like migrations. To undo the last batch of seeder, you can use the db:seed --class command with the --reverse option.

 

Using seeder in Laravel makes it easy to populate the database with initial data or create dummy data for testing purposes. It allows you to quickly insert data into tables without manual intervention.