Laravel has this amazing feature of seeding database with test data using seed classes. These classes are stored in database/seeds.

Here in this document, we will discuss about how to seed data effectively.

1. Avoid seed duplication using updateOrCreate()

It is uncommon for data seeding code to run more than once but ignorance is not an option. Below is an example of bad practice:

public function run()
{
    $items = [            
        ['id' => 1, 'title' => 'Administrator'],
        ['id' => 2, 'title' => 'Simple user'],
    ];

    foreach ($items as $item) {
        Role::create($item);
    }
}

Above code is a bad practice in a sense that if we try to run this code twice it will fail because of duplicate IDs. Some beginners may think that removing ID will solve that problem but rather than solving it will create much bigger problems in future. For solving these problems, updateOrCreate() is the best option:

foreach ($items as $item) {
    Role::updateOrCreate(['id' => $item['id']], $item);
}

If we run the above code twice, it updates existing data if it exists and also creates new data. You can get more details about updateOrCreate() by clicking here.

2. Run only one Seeder Class

Seeder consists of multiple seeder classes hence most of the people run the whole seeder class. Laravel also provides this amazing feature of running specific seeder class.

php artisan db:seed

Many people run the above code which imports all data. But one can also restrict data to only required one.

php artisan db:seed --class=UsersTableSeeder

The above code only seeds data in User table.

#tutorials #dataseeding #data visualization

Data Seeding Tips And Tricks
1.20 GEEK