When working with web applications you know the need for testing with sample data in your applications during development. This is extremely useful because testing with various sample data allows you to likely detect bugs you otherwise would have overlooked. Meaningful sample data also provides a useful way of showcasing the application for others, without having the typical manually entered John Doe entries over and over again.
Laravel provides a tool to add sample data to your databases automatically. They call it database seeding. It is the processes of adding data to a database after migrations. You can create seeding scripts with PHP, so they can essentially include any logic you desire, to create the sample data. That means you both have access to randomizer functions, automated calculations, or you could even include external data lists to make the sample data more realistic. E.g. you could randomly combine names from a list of first names and last names to generate usernames and email addresses. This would make user interface tests look more realistic.
Create a database seeder script
You can build seeder scripts using Artisan like below:
php artisan make:seeder UsersSeeder
Normally the seeder only contains a “run” method, but since it is a class, you could add whatever other methods you need to help building your sample data. This could be functions to include or randomize data like described above.
Below is a sample seeder class for the user table, which basically just adds random entries of user names and email addresses.
<?php use Illuminate\Database\Seeder; use Illuminate\Database\Eloquent\Model; class DatabaseSeeder extends Seeder { /** * Run the user seeder. * * @return void */ public function run() { DB::table('users')->insert([ 'name' => str_random(8), 'email' => str_random(12).'@mail.com', ]); } } ?>
Running your seeder
You can run all seeder scripts at once or execute individual ones with Artisan using the commands below:
// Run all seeders php artisan db:seed // Run specific seeder php artisan db:seed --class=UsersSeeder
Using model factories
Creating seeding scripts like above for each of your models may be useful if you have smaller projects, but as soon as you run into large and complex data structures, you may benefit from using model factories for your seeding. Model factories allow you to conveniently and centrally organize model data creation used for testing and seeding. Thereby you can define rules and randomization for your model generation in one place, and draw from that whenever you need sample data, being both for seeding and unit testing.
Summary
Working with seeders makes it super easy to add sample data to your database, and the scripts can be generated and executed via Artisan, so you only need to add the actual seeding logic.
No comments yet (leave a comment)